wikidata.datavalue — Interpreting datavalues

This module provides the decoder interface for customizing how datavalues are decoded, and the default Decoder implementation.

Technically the interface is just a callable so that its implementation doesn’t necessarily have to be an instance of Decoder or its subclass, but only need to satify:

typing.Callable[[wikidata.client.Client, str, typing.Mapping[str, object]],

New in version 0.3.0.

exception wikidata.datavalue.DatavalueError(*args, **kwargs)

Exception raised during decoding datavalues. It subclasses ValueError as well.


The datavalue which caused the decoding error.

class wikidata.datavalue.Decoder

Decode the given datavalue to a value of the appropriate Python type. For extensibility it uses visitor pattern and is intended to be subclassed. To customize decoding of datavalues subclass it and configure datavalue_decoder option of Client to the customized decoder.

It automatically invokes an appropriate visitor method using a simple rule of name: {datatype}__{datavalue[type]}. For example, if the following call to a decoder was made:

decoder(client, 'mydatatype', {'type': 'mytype', 'value': '...'})

it’s delegated to the following visitor method call:

decoder.mydatatype__mytype(client, {‘type’: ‘mytype’, ‘value’: ‘...’})

If a decoder failed to find a visitor method matched to {datatype}__{datavalue[type]} pattern it secondly try to find a general version of visitor method: {datavalue[type]} which lacks double underscores. For example, for the following call:

decoder(client, 'mydatatype', {'type': 'mytype', 'value': '...'})

It firstly try to find the following visitor method:


but if there’s no such method it secondly try to find the following general visitor method:


This twice-try dispatch is useful when to make a visitor method to be matched regardless of datatype.

If its datavalue[type] contains hyphens they’re replaced by underscores. For example:

decoder(client, 'string',
        {'type': 'wikibase-entityid', 'value': 'a text value'})

the above call is delegated to the following visitor method call:

    #     Note that the ^ underscore
    {'type': 'wikibase-entityid', 'value': 'a text value'}