Skip to content

# `` custom_datatype

RDFLib can map between RDF data-typed literals and Python objects.

Mapping for integers, floats, dateTimes, etc. are already added, but you can also add your own.

This example shows how `bind` lets you register new mappings between literal datatypes and Python objects

Attributes:

- `EG` –
- `c` –
- `g` –
- `g2` –
- `l` –
- `l2` –

## `` EG `module-attribute`

    EG = Namespace('http://example.com/')

## `` c `module-attribute`

    c = complex(2, 3)

## `` g `module-attribute`

    g = Graph()

## `` g2 `module-attribute`

    g2 = parse(data=serialize())

## `` l `module-attribute`

    l = Literal(c)

## `` l2 `module-attribute`

    l2 = list(g2)[0]

ce: false show_docstring_attributes: false show_docstring_functions: false show_docstring_modules: false show_docstring_classes: false show_signature: false show_signature_annotations: false show_signature_type_parameters: false show_docstring_other_parameters: false show_docstring_parameters: false show_docstring_raises: false show_docstring_receives: false show_docstring_returns: false summary: false show_if_no_docstring: false

    from rdflib import XSD, Graph, Literal, Namespace, term

    if __name__ == "__main__":
        # Complex numbers are not registered by default
        # No custom constructor/serializer needed since
        # complex('(2+3j)') works fine
        term.bind(XSD.complexNumber, complex)

        # Create a complex number RDFlib Literal
        EG = Namespace("http://example.com/")
        c = complex(2, 3)
        l = Literal(c)  # noqa: E741

        # Add it to a graph
        g = Graph()
        g.add((EG.mysubject, EG.myprop, l))
        # Print the triple to see what it looks like
        print(list(g)[0])
        # prints: (
        #           rdflib.term.URIRef('http://example.com/mysubject'),
        #           rdflib.term.URIRef('http://example.com/myprop'),
        #           rdflib.term.Literal(
        #               '(2+3j)',
        #               datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#complexNumber')
        #           )
        #         )

        # Round-trip through n3 serialize/parse
        g2 = Graph().parse(data=g.serialize())

        l2 = list(g2)[0]
        print(l2)

        # Compare with the original python complex object (should be True)
        # l2[2] is the object of the triple
        assert isinstance(l2[2], Literal)
        print(l2[2].value == c)