rdflib package

Subpackages

Submodules

rdflib.collection module

class rdflib.collection.Collection(graph, uri, seq=[])[source]

Bases: object

See “Emulating container types”: https://docs.python.org/reference/datamodel.html#emulating-container-types

>>> from rdflib.term import Literal
>>> from rdflib.graph import Graph
>>> from pprint import pprint
>>> listname = BNode()
>>> g = Graph('Memory')
>>> listItem1 = BNode()
>>> listItem2 = BNode()
>>> g.add((listname, RDF.first, Literal(1))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listname, RDF.rest, listItem1)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem1, RDF.first, Literal(2))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem1, RDF.rest, listItem2)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem2, RDF.rest, RDF.nil)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem2, RDF.first, Literal(3))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> c = Collection(g,listname)
>>> pprint([term.n3() for term in c])
[u'"1"^^<http://www.w3.org/2001/XMLSchema#integer>',
 u'"2"^^<http://www.w3.org/2001/XMLSchema#integer>',
 u'"3"^^<http://www.w3.org/2001/XMLSchema#integer>']
>>> Literal(1) in c
True
>>> len(c)
3
>>> c._get_container(1) == listItem1
True
>>> c.index(Literal(2)) == 1
True
Parameters:
__delitem__(key)[source]
>>> from rdflib.namespace import RDF, RDFS
>>> from rdflib import Graph
>>> from pprint import pformat
>>> g = Graph()
>>> a = BNode('foo')
>>> b = BNode('bar')
>>> c = BNode('baz')
>>> g.add((a, RDF.first, RDF.type)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((a, RDF.rest, b)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b, RDF.first, RDFS.label)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b, RDF.rest, c)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c, RDF.first, RDFS.comment)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c, RDF.rest, RDF.nil)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(g)
6
>>> def listAncestry(node, graph):
...   for i in graph.subjects(RDF.rest, node):
...     yield i
>>> [str(node.n3())
...   for node in g.transitiveClosure(listAncestry, RDF.nil)]
['_:baz', '_:bar', '_:foo']
>>> lst = Collection(g, a)
>>> len(lst)
3
>>> b == lst._get_container(1)
True
>>> c == lst._get_container(2)
True
>>> del lst[1]
>>> len(lst)
2
>>> len(g)
4
Parameters:

key (int) –

Return type:

None

__dict__ = mappingproxy({'__module__': 'rdflib.collection', '__doc__': '\n    See "Emulating container types":\n    https://docs.python.org/reference/datamodel.html#emulating-container-types\n\n    >>> from rdflib.term import Literal\n    >>> from rdflib.graph import Graph\n    >>> from pprint import pprint\n    >>> listname = BNode()\n    >>> g = Graph(\'Memory\')\n    >>> listItem1 = BNode()\n    >>> listItem2 = BNode()\n    >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS\n    <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n    >>> c = Collection(g,listname)\n    >>> pprint([term.n3() for term in c])\n    [u\'"1"^^<http://www.w3.org/2001/XMLSchema#integer>\',\n     u\'"2"^^<http://www.w3.org/2001/XMLSchema#integer>\',\n     u\'"3"^^<http://www.w3.org/2001/XMLSchema#integer>\']\n\n    >>> Literal(1) in c\n    True\n    >>> len(c)\n    3\n    >>> c._get_container(1) == listItem1\n    True\n    >>> c.index(Literal(2)) == 1\n    True\n    ', '__init__': <function Collection.__init__>, 'n3': <function Collection.n3>, '_get_container': <function Collection._get_container>, '__len__': <function Collection.__len__>, 'index': <function Collection.index>, '__getitem__': <function Collection.__getitem__>, '__setitem__': <function Collection.__setitem__>, '__delitem__': <function Collection.__delitem__>, '__iter__': <function Collection.__iter__>, '_end': <function Collection._end>, 'append': <function Collection.append>, '__iadd__': <function Collection.__iadd__>, 'clear': <function Collection.clear>, '__dict__': <attribute '__dict__' of 'Collection' objects>, '__weakref__': <attribute '__weakref__' of 'Collection' objects>, '__annotations__': {}})
__getitem__(key)[source]

TODO

Parameters:

key (int) –

Return type:

Node

__iadd__(other)[source]
Parameters:

other (Iterable[Node]) –

__init__(graph, uri, seq=[])[source]
Parameters:
__iter__()[source]

Iterator over items in Collections

Return type:

Iterator[Node]

__len__()[source]

length of items in collection.

Return type:

int

__module__ = 'rdflib.collection'
__setitem__(key, value)[source]

TODO

Parameters:
Return type:

None

__weakref__

list of weak references to the object (if defined)

append(item)[source]
>>> from rdflib.term import Literal
>>> from rdflib.graph import Graph
>>> listname = BNode()
>>> g = Graph()
>>> c = Collection(g,listname,[Literal(1),Literal(2)])
>>> links = [
...     list(g.subjects(object=i, predicate=RDF.first))[0] for i in c]
>>> len([i for i in links if (i, RDF.rest, RDF.nil) in g])
1
Parameters:

item (Node) –

Return type:

Collection

clear()[source]
index(item)[source]

Returns the 0-based numerical index of the item in the list

Parameters:

item (Node) –

Return type:

int

n3()[source]
>>> from rdflib.term import Literal
>>> from rdflib.graph import Graph
>>> listname = BNode()
>>> g = Graph('Memory')
>>> listItem1 = BNode()
>>> listItem2 = BNode()
>>> g.add((listname, RDF.first, Literal(1))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listname, RDF.rest, listItem1)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem1, RDF.first, Literal(2))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem1, RDF.rest, listItem2)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem2, RDF.rest, RDF.nil)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((listItem2, RDF.first, Literal(3))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> c = Collection(g, listname)
>>> print(c.n3()) 
( "1"^^<http://www.w3.org/2001/XMLSchema#integer>
:rtype: :py:class:`str`

rdflib.compare module

A collection of utilities for canonicalizing and inspecting graphs.

Among other things, they solve of the problem of deterministic bnode comparisons.

Warning: the time to canonicalize bnodes may increase exponentially on degenerate larger graphs. Use with care!

Example of comparing two graphs:

>>> g1 = Graph().parse(format='n3', data='''
...     @prefix : <http://example.org/ns#> .
...     <http://example.org> :rel
...         <http://example.org/same>,
...         [ :label "Same" ],
...         <http://example.org/a>,
...         [ :label "A" ] .
... ''')
>>> g2 = Graph().parse(format='n3', data='''
...     @prefix : <http://example.org/ns#> .
...     <http://example.org> :rel
...         <http://example.org/same>,
...         [ :label "Same" ],
...         <http://example.org/b>,
...         [ :label "B" ] .
... ''')
>>>
>>> iso1 = to_isomorphic(g1)
>>> iso2 = to_isomorphic(g2)

These are not isomorphic:

>>> iso1 == iso2
False

Diff the two graphs:

>>> in_both, in_first, in_second = graph_diff(iso1, iso2)

Present in both:

>>> def dump_nt_sorted(g):
...     for l in sorted(g.serialize(format='nt').splitlines()):
...         if l: print(l.decode('ascii'))

>>> dump_nt_sorted(in_both) 
<http://example.org>
    <http://example.org/ns#rel> <http://example.org/same> .
<http://example.org>
    <http://example.org/ns#rel> _:cbcaabaaba17fecbc304a64f8edee4335e .
_:cbcaabaaba17fecbc304a64f8edee4335e
    <http://example.org/ns#label> "Same" .

Only in first:

>>> dump_nt_sorted(in_first) 
<http://example.org>
    <http://example.org/ns#rel> <http://example.org/a> .
<http://example.org>
    <http://example.org/ns#rel> _:cb124e4c6da0579f810c0ffe4eff485bd9 .
_:cb124e4c6da0579f810c0ffe4eff485bd9
    <http://example.org/ns#label> "A" .

Only in second:

>>> dump_nt_sorted(in_second) 
<http://example.org>
    <http://example.org/ns#rel> <http://example.org/b> .
<http://example.org>
    <http://example.org/ns#rel> _:cb558f30e21ddfc05ca53108348338ade8 .
_:cb558f30e21ddfc05ca53108348338ade8
    <http://example.org/ns#label> "B" .
class rdflib.compare.IsomorphicGraph(**kwargs)[source]

Bases: ConjunctiveGraph

An implementation of the RGDA1 graph digest algorithm.

An implementation of RGDA1 (publication below), a combination of Sayers & Karp’s graph digest algorithm using sum and SHA-256 <http://www.hpl.hp.com/techreports/2003/HPL-2003-235R1.pdf> and traces <http://pallini.di.uniroma1.it>, an average case polynomial time algorithm for graph canonicalization.

McCusker, J. P. (2015). WebSig: A Digital Signature Framework for the Web. Rensselaer Polytechnic Institute, Troy, NY. http://gradworks.umi.com/3727015.pdf

__eq__(other)[source]

Graph isomorphism testing.

__hash__()[source]

Return hash(self).

__init__(**kwargs)[source]
__module__ = 'rdflib.compare'
__ne__(other)[source]

Negative graph isomorphism testing.

graph_digest(stats=None)[source]

Synonym for IsomorphicGraph.internal_hash.

internal_hash(stats=None)[source]

This is defined instead of __hash__ to avoid a circular recursion scenario with the Memory store for rdflib which requires a hash lookup in order to return a generator of triples.

rdflib.compare.graph_diff(g1, g2)[source]

Returns three sets of triples: “in both”, “in first” and “in second”.

Parameters:
Return type:

Tuple[Graph, Graph, Graph]

rdflib.compare.isomorphic(graph1, graph2)[source]

Compare graph for equality.

Uses an algorithm to compute unique hashes which takes bnodes into account.

Examples:

>>> g1 = Graph().parse(format='n3', data='''
...     @prefix : <http://example.org/ns#> .
...     <http://example.org> :rel <http://example.org/a> .
...     <http://example.org> :rel <http://example.org/b> .
...     <http://example.org> :rel [ :label "A bnode." ] .
... ''')
>>> g2 = Graph().parse(format='n3', data='''
...     @prefix ns: <http://example.org/ns#> .
...     <http://example.org> ns:rel [ ns:label "A bnode." ] .
...     <http://example.org> ns:rel <http://example.org/b>,
...             <http://example.org/a> .
... ''')
>>> isomorphic(g1, g2)
True

>>> g3 = Graph().parse(format='n3', data='''
...     @prefix : <http://example.org/ns#> .
...     <http://example.org> :rel <http://example.org/a> .
...     <http://example.org> :rel <http://example.org/b> .
...     <http://example.org> :rel <http://example.org/c> .
... ''')
>>> isomorphic(g1, g3)
False
Parameters:
Return type:

bool

rdflib.compare.similar(g1, g2)[source]

Checks if the two graphs are “similar”.

Checks if the two graphs are “similar”, by comparing sorted triples where all bnodes have been replaced by a singular mock bnode (the _MOCK_BNODE).

This is a much cheaper, but less reliable, alternative to the comparison algorithm in isomorphic.

Parameters:
rdflib.compare.to_canonical_graph(g1, stats=None)[source]

Creates a canonical, read-only graph.

Creates a canonical, read-only graph where all bnode id:s are based on deterministical SHA-256 checksums, correlated with the graph contents.

Parameters:
Return type:

ReadOnlyGraphAggregate

rdflib.compare.to_isomorphic(graph)[source]
Parameters:

graph (Graph) –

Return type:

IsomorphicGraph

rdflib.compat module

Utility functions and objects to ease Python 2/3 compatibility, and different versions of support libraries.

rdflib.compat.ascii(stream)[source]
rdflib.compat.bopen(*args, **kwargs)[source]
rdflib.compat.cast_bytes(s, enc='utf-8')[source]
rdflib.compat.decodeStringEscape(s)[source]
rdflib.compat.decodeUnicodeEscape(escaped)[source]
Parameters:

escaped (str) –

Return type:

str

rdflib.compat.sign(n)[source]

rdflib.container module

class rdflib.container.Alt(graph, uri, seq=[])[source]

Bases: Container

__init__(graph, uri, seq=[])[source]

Creates a Container

Parameters:
  • graph – a Graph instance

  • uri – URI or Blank Node of the Container

  • seq – the elements of the Container

  • rtype – the type of Container, one of “Bag”, “Seq” or “Alt”

__module__ = 'rdflib.container'
anyone()[source]
class rdflib.container.Bag(graph, uri, seq=[])[source]

Bases: Container

Unordered container (no preference order of elements)

__init__(graph, uri, seq=[])[source]

Creates a Container

Parameters:
  • graph – a Graph instance

  • uri – URI or Blank Node of the Container

  • seq – the elements of the Container

  • rtype – the type of Container, one of “Bag”, “Seq” or “Alt”

__module__ = 'rdflib.container'
class rdflib.container.Container(graph, uri, seq=[], rtype='Bag')[source]

Bases: object

A class for constructing RDF containers, as per https://www.w3.org/TR/rdf11-mt/#rdf-containers

Basic usage, creating a Bag and adding to it:

>>> from rdflib import Graph, BNode, Literal, Bag
>>> g = Graph()
>>> b = Bag(g, BNode(), [Literal("One"), Literal("Two"), Literal("Three")])
>>> print(g.serialize(format="turtle"))
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

[] a rdf:Bag ;
    rdf:_1 "One" ;
    rdf:_2 "Two" ;
    rdf:_3 "Three" .



>>> # print out an item using an index reference
>>> print(b[2])
Two

>>> # add a new item
>>> b.append(Literal("Hello")) 
<rdflib.container.Bag object at ...>
>>> print(g.serialize(format="turtle"))
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

[] a rdf:Bag ;
    rdf:_1 "One" ;
    rdf:_2 "Two" ;
    rdf:_3 "Three" ;
    rdf:_4 "Hello" .

__delitem__(key)[source]

Removing the item with index key or predicate rdf:_key

__dict__ = mappingproxy({'__module__': 'rdflib.container', '__doc__': 'A class for constructing RDF containers, as per https://www.w3.org/TR/rdf11-mt/#rdf-containers\n\n    Basic usage, creating a ``Bag`` and adding to it::\n\n        >>> from rdflib import Graph, BNode, Literal, Bag\n        >>> g = Graph()\n        >>> b = Bag(g, BNode(), [Literal("One"), Literal("Two"), Literal("Three")])\n        >>> print(g.serialize(format="turtle"))\n        @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n        <BLANKLINE>\n        [] a rdf:Bag ;\n            rdf:_1 "One" ;\n            rdf:_2 "Two" ;\n            rdf:_3 "Three" .\n        <BLANKLINE>\n        <BLANKLINE>\n\n        >>> # print out an item using an index reference\n        >>> print(b[2])\n        Two\n\n        >>> # add a new item\n        >>> b.append(Literal("Hello")) # doctest: +ELLIPSIS\n        <rdflib.container.Bag object at ...>\n        >>> print(g.serialize(format="turtle"))\n        @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n        <BLANKLINE>\n        [] a rdf:Bag ;\n            rdf:_1 "One" ;\n            rdf:_2 "Two" ;\n            rdf:_3 "Three" ;\n            rdf:_4 "Hello" .\n        <BLANKLINE>\n        <BLANKLINE>\n\n    ', '__init__': <function Container.__init__>, 'n3': <function Container.n3>, '_get_container': <function Container._get_container>, '__len__': <function Container.__len__>, 'type_of_conatiner': <function Container.type_of_conatiner>, 'index': <function Container.index>, '__getitem__': <function Container.__getitem__>, '__setitem__': <function Container.__setitem__>, '__delitem__': <function Container.__delitem__>, 'items': <function Container.items>, 'end': <function Container.end>, 'append': <function Container.append>, 'append_multiple': <function Container.append_multiple>, 'clear': <function Container.clear>, '__dict__': <attribute '__dict__' of 'Container' objects>, '__weakref__': <attribute '__weakref__' of 'Container' objects>, '__annotations__': {}})
__getitem__(key)[source]

Returns item of the container at index key

__init__(graph, uri, seq=[], rtype='Bag')[source]

Creates a Container

Parameters:
  • graph – a Graph instance

  • uri – URI or Blank Node of the Container

  • seq – the elements of the Container

  • rtype – the type of Container, one of “Bag”, “Seq” or “Alt”

__len__()[source]

Number of items in container

__module__ = 'rdflib.container'
__setitem__(key, value)[source]

Sets the item at index key or predicate rdf:_key of the container to value

__weakref__

list of weak references to the object (if defined)

append(item)[source]

Adding item to the end of the container

append_multiple(other)[source]

Adding multiple elements to the container to the end which are in python list other

clear()[source]

Removing all elements from the container

end()[source]
index(item)[source]

Returns the 1-based numerical index of the item in the container

items()[source]

Returns a list of all items in the container

n3()[source]
type_of_conatiner()[source]
exception rdflib.container.NoElementException(message='rdf:Alt Container is empty')[source]

Bases: Exception

__init__(message='rdf:Alt Container is empty')[source]
__module__ = 'rdflib.container'
__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

class rdflib.container.Seq(graph, uri, seq=[])[source]

Bases: Container

__init__(graph, uri, seq=[])[source]

Creates a Container

Parameters:
  • graph – a Graph instance

  • uri – URI or Blank Node of the Container

  • seq – the elements of the Container

  • rtype – the type of Container, one of “Bag”, “Seq” or “Alt”

__module__ = 'rdflib.container'
add_at_position(pos, item)[source]

rdflib.events module

Dirt Simple Events

A Dispatcher (or a subclass of Dispatcher) stores event handlers that are ‘fired’ simple event objects when interesting things happen.

Create a dispatcher:

>>> d = Dispatcher()

Now create a handler for the event and subscribe it to the dispatcher to handle Event events. A handler is a simple function or method that accepts the event as an argument:

>>> def handler1(event): print(repr(event))
>>> d.subscribe(Event, handler1) 
<rdflib.events.Dispatcher object at ...>

Now dispatch a new event into the dispatcher, and see handler1 get fired:

>>> d.dispatch(Event(foo='bar', data='yours', used_by='the event handlers'))
<rdflib.events.Event ['data', 'foo', 'used_by']>
class rdflib.events.Dispatcher[source]

Bases: object

An object that can dispatch events to a privately managed group of subscribers.

__annotations__ = {'_dispatch_map': 'Optional[Dict[Any, Any]]'}
__dict__ = mappingproxy({'__module__': 'rdflib.events', '__annotations__': {'_dispatch_map': 'Optional[Dict[Any, Any]]'}, '__doc__': '\n    An object that can dispatch events to a privately managed group of\n    subscribers.\n    ', '_dispatch_map': None, 'set_map': <function Dispatcher.set_map>, 'get_map': <function Dispatcher.get_map>, 'subscribe': <function Dispatcher.subscribe>, 'dispatch': <function Dispatcher.dispatch>, '__dict__': <attribute '__dict__' of 'Dispatcher' objects>, '__weakref__': <attribute '__weakref__' of 'Dispatcher' objects>})
__module__ = 'rdflib.events'
__weakref__

list of weak references to the object (if defined)

dispatch(event)[source]

Dispatch the given event to the subscribed handlers for the event’s type

get_map()[source]
set_map(amap)[source]
Parameters:

amap (Dict[Any, Any]) –

subscribe(event_type, handler)[source]

Subscribe the given handler to an event_type. Handlers are called in the order they are subscribed.

class rdflib.events.Event(**kw)[source]

Bases: object

An event is a container for attributes. The source of an event creates this object, or a subclass, gives it any kind of data that the events handlers need to handle the event, and then calls notify(event).

The target of an event registers a function to handle the event it is interested with subscribe(). When a sources calls notify(event), each subscriber to that event will be called in no particular order.

__dict__ = mappingproxy({'__module__': 'rdflib.events', '__doc__': '\n    An event is a container for attributes.  The source of an event\n    creates this object, or a subclass, gives it any kind of data that\n    the events handlers need to handle the event, and then calls\n    notify(event).\n\n    The target of an event registers a function to handle the event it\n    is interested with subscribe().  When a sources calls\n    notify(event), each subscriber to that event will be called in no\n    particular order.\n    ', '__init__': <function Event.__init__>, '__repr__': <function Event.__repr__>, '__dict__': <attribute '__dict__' of 'Event' objects>, '__weakref__': <attribute '__weakref__' of 'Event' objects>, '__annotations__': {}})
__init__(**kw)[source]
__module__ = 'rdflib.events'
__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

rdflib.exceptions module

TODO:

exception rdflib.exceptions.Error(msg=None)[source]

Bases: Exception

Base class for rdflib exceptions.

Parameters:

msg (Optional[str]) –

__init__(msg=None)[source]
Parameters:

msg (Optional[str]) –

__module__ = 'rdflib.exceptions'
__weakref__

list of weak references to the object (if defined)

exception rdflib.exceptions.ParserError(msg)[source]

Bases: Error

RDF Parser error.

Parameters:

msg (str) –

__init__(msg)[source]
Parameters:

msg (str) –

__module__ = 'rdflib.exceptions'
__str__()[source]

Return str(self).

Return type:

str

exception rdflib.exceptions.UniquenessError(values)[source]

Bases: Error

A uniqueness assumption was made in the context, and that is not true

Parameters:

values (Any) –

__init__(values)[source]
Parameters:

values (Any) –

__module__ = 'rdflib.exceptions'

rdflib.graph module

RDFLib defines the following kinds of Graphs:

Graph

An RDF graph is a set of RDF triples. Graphs support the python in operator, as well as iteration and some operations like union, difference and intersection.

see Graph

Conjunctive Graph

A Conjunctive Graph is the most relevant collection of graphs that are considered to be the boundary for closed world assumptions. This boundary is equivalent to that of the store instance (which is itself uniquely identified and distinct from other instances of Store that signify other Conjunctive Graphs). It is equivalent to all the named graphs within it and associated with a _default_ graph which is automatically assigned a BNode for an identifier - if one isn’t given.

see ConjunctiveGraph

Quoted graph

The notion of an RDF graph [14] is extended to include the concept of a formula node. A formula node may occur wherever any other kind of node can appear. Associated with a formula node is an RDF graph that is completely disjoint from all other graphs; i.e. has no nodes in common with any other graph. (It may contain the same labels as other RDF graphs; because this is, by definition, a separate graph, considerations of tidiness do not apply between the graph at a formula node and any other graph.)

This is intended to map the idea of “{ N3-expression }” that is used by N3 into an RDF graph upon which RDF semantics is defined.

see QuotedGraph

Dataset

The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The primary term is “graphs in the datasets” and not “contexts with quads” so there is a separate method to set/retrieve a graph in a dataset and to operate with dataset graphs. As a consequence of this approach, dataset graphs cannot be identified with blank nodes, a name is always required (RDFLib will automatically add a name if one is not provided at creation time). This implementation includes a convenience method to directly add a single quad to a dataset graph.

see Dataset

Working with graphs

Instantiating Graphs with default store (Memory) and default identifier (a BNode):

>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.stores.memory.Memory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>

Instantiating Graphs with a Memory store and an identifier - <https://rdflib.github.io>:

>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g)  
"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
 [a rdflib:Store;rdfs:label 'Memory']."

Creating a ConjunctiveGraph - The top level container for all named Graphs in a “database”:

>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']]."

Adding / removing reified triples to Graph and iterating over it directly or via triple pattern:

>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
...     URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
4
>>> for s, p, o in g:
...     print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
>>> for s, p, o in g.triples((None, RDF.object, None)):
...     print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
3

None terms in calls to triples() can be thought of as “open variables”.

Graph support set-theoretic operators, you can add/subtract graphs, as well as intersection (with multiplication operator g1*g2) and xor (g1 ^ g2).

Note that BNode IDs are kept when doing set-theoretic operations, this may or may not be what you want. Two named graphs within the same application probably want share BNode IDs, two graphs with data from different sources probably not. If your BNode IDs are all generated by RDFLib they are UUIDs and unique.

>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef("http://example.com/foo")
>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(g1 + g2)  # adds bing as label
3
>>> len(g1 - g2)  # removes foo
1
>>> len(g1 * g2)  # only foo
1
>>> g1 += g2  # now g1 contains everything

Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:

>>> store = plugin.get("Memory", Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.type, RDF.Statement)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.type, RDF.Statement)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
...     URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.object, Literal(
...     'The top-level aggregate graph - The sum ' +
...     'of all named graphs within a Store'))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
...     RDF.type, RDF.Statement)))
2

ConjunctiveGraphs have a quads() method which returns quads instead of triples, where the fourth item is the Graph (or subclass thereof) instance in which the triple was asserted:

>>> uniqueGraphNames = set(
...     [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
...     ).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set(
...     [graph.identifier for s, p, o, graph in unionGraph.quads(
...     (None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2

Parsing N3 from a string

>>> g2 = Graph()
>>> src = '''
... @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
...   rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
...   rdf:predicate rdfs:label;
...   rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format="n3")
>>> print(len(g2))
4

Using Namespace class:

>>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
rdflib.term.URIRef('https://rdflib.github.io/Graph')
class rdflib.graph.BatchAddGraph(graph, batch_size=1000, batch_addn=False)[source]

Bases: object

Wrapper around graph that turns batches of calls to Graph’s add (and optionally, addN) into calls to batched calls to addN`.

Parameters:
  • graph: The graph to wrap

  • batch_size: The maximum number of triples to buffer before passing to Graph’s addN

  • batch_addn: If True, then even calls to addN will be batched according to batch_size

graph: The wrapped graph count: The number of triples buffered since initialization or the last call to reset batch: The current buffer of triples

Parameters:
  • graph (Graph) –

  • batch_size (int) –

  • batch_addn (bool) –

__dict__ = mappingproxy({'__module__': 'rdflib.graph', '__doc__': "\n    Wrapper around graph that turns batches of calls to Graph's add\n    (and optionally, addN) into calls to batched calls to addN`.\n\n    :Parameters:\n\n      - graph: The graph to wrap\n      - batch_size: The maximum number of triples to buffer before passing to\n        Graph's addN\n      - batch_addn: If True, then even calls to `addN` will be batched according to\n        batch_size\n\n    graph: The wrapped graph\n    count: The number of triples buffered since initialization or the last call to reset\n    batch: The current buffer of triples\n\n    ", '__init__': <function BatchAddGraph.__init__>, 'reset': <function BatchAddGraph.reset>, 'add': <function BatchAddGraph.add>, 'addN': <function BatchAddGraph.addN>, '__enter__': <function BatchAddGraph.__enter__>, '__exit__': <function BatchAddGraph.__exit__>, '__dict__': <attribute '__dict__' of 'BatchAddGraph' objects>, '__weakref__': <attribute '__weakref__' of 'BatchAddGraph' objects>, '__annotations__': {}})
__enter__()[source]
Return type:

BatchAddGraph

__exit__(*exc)[source]
Return type:

None

__init__(graph, batch_size=1000, batch_addn=False)[source]
Parameters:
  • graph (Graph) –

  • batch_size (int) –

  • batch_addn (bool) –

__module__ = 'rdflib.graph'
__weakref__

list of weak references to the object (if defined)

add(triple_or_quad)[source]

Add a triple to the buffer

Parameters:
Return type:

BatchAddGraph

addN(quads)[source]
Parameters:

quads (Iterable[Tuple[Node, Node, Node, Graph]]) –

Return type:

BatchAddGraph

reset()[source]

Manually clear the buffered triples and reset the count to zero

Return type:

BatchAddGraph

class rdflib.graph.ConjunctiveGraph(store='default', identifier=None, default_graph_base=None)[source]

Bases: Graph

A ConjunctiveGraph is an (unnamed) aggregation of all the named graphs in a store.

It has a default graph, whose name is associated with the graph throughout its life. __init__() can take an identifier to use as the name of this default graph or it will assign a BNode.

All methods that add triples work against this default graph.

All queries are carried out against the union of all graphs.

Parameters:
__contains__(triple_or_quad)[source]

Support for ‘triple/quad in graph’ syntax

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]], Tuple[Optional[Node], Union[Path, Node, None], Optional[Node], Optional[Graph]]]) –

Return type:

bool

__init__(store='default', identifier=None, default_graph_base=None)[source]
Parameters:
__len__()[source]

Number of triples in the entire conjunctive graph

Return type:

int

__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]

__str__()[source]

Return str(self).

Return type:

str

add(triple_or_quad)[source]

Add a triple or quad to the store.

if a triple is given it is added to the default context

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

addN(quads)[source]

Add a sequence of triples with context

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

context_id(uri, context_id=None)[source]

URI#context

Parameters:
Return type:

URIRef

contexts(triple=None)[source]

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

get_context(identifier, quoted=False, base=None)[source]

Return a context graph for the given identifier

identifier must be a URIRef or BNode.

Parameters:
Return type:

Graph

get_graph(identifier)[source]

Returns the graph identified by given identifier

Parameters:

identifier (IdentifiedNode) –

Return type:

Optional[Graph]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse source adding the resulting triples to its own context (sub graph of this graph).

See rdflib.graph.Graph.parse() for documentation on arguments.

If the source is in a format that does not support named graphs it’s triples will be added to the default graph (i.e. Dataset.default_context).

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root context.

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Changed in 7.0: The publicID argument is no longer used as the identifier (i.e. name) of the default graph as was the case before version 7.0. In the case of sources that do not support named graphs, the publicID parameter will also not be used as the name for the graph that the data is loaded into, and instead the triples from sources that do not support named graphs will be loaded into the default graph (i.e. ConjunctionGraph.default_context).

Parameters:
Return type:

Graph

quads(triple_or_quad=None)[source]

Iterate over all the quads in the entire conjunctive graph

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], Optional[Node], Optional[Graph]], None]) –

Return type:

Generator[Tuple[Node, Node, Node, Optional[Graph]], None, None]

remove(triple_or_quad)[source]

Removes a triple or quads

if a triple is given it is removed from all contexts

a quad is removed from the given context only

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

remove_context(context)[source]

Removes the given context from the graph

Parameters:

context (Graph) –

Return type:

None

triples(triple_or_quad, context=None)[source]

Iterate over all the triples in the entire conjunctive graph

For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.

Parameters:
Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

triples_choices(triple, context=None)[source]

Iterate over all the triples in the entire conjunctive graph

Parameters:
Return type:

Generator[Tuple[Node, Node, Node], None, None]

class rdflib.graph.Dataset(store='default', default_union=False, default_graph_base=None)[source]

Bases: ConjunctiveGraph

RDF 1.1 Dataset. Small extension to the Conjunctive Graph: - the primary term is graphs in the datasets and not contexts with quads, so there is a separate method to set/retrieve a graph in a dataset and operate with graphs - graphs cannot be identified with blank nodes - added a method to directly add a single quad

Examples of usage:

>>> # Create a new Dataset
>>> ds = Dataset()
>>> # simple triples goes to default graph
>>> ds.add((URIRef("http://example.org/a"),
...    URIRef("http://www.example.org/b"),
...    Literal("foo")))  
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>>
>>> # Create a graph in the dataset, if the graph name has already been
>>> # used, the corresponding graph will be returned
>>> # (ie, the Dataset keeps track of the constituent graphs)
>>> g = ds.graph(URIRef("http://www.example.com/gr"))
>>>
>>> # add triples to the new graph as usual
>>> g.add(
...     (URIRef("http://example.org/x"),
...     URIRef("http://example.org/y"),
...     Literal("bar")) ) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> # alternatively: add a quad to the dataset -> goes to the graph
>>> ds.add(
...     (URIRef("http://example.org/x"),
...     URIRef("http://example.org/z"),
...     Literal("foo-bar"),g) ) 
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>>
>>> # querying triples return them all regardless of the graph
>>> for t in ds.triples((None,None,None)):  
...     print(t)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"))
>>>
>>> # querying quads() return quads; the fourth argument can be unrestricted
>>> # (None) or restricted to a graph
>>> for q in ds.quads((None, None, None, None)):  
...     print(q)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"),
 None)
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>>
>>> # unrestricted looping is equivalent to iterating over the entire Dataset
>>> for q in ds:  
...     print(q)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"),
 None)
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>>
>>> # resticting iteration to a graph:
>>> for q in ds.quads((None, None, None, g)):  
...     print(q)  
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>> # Note that in the call above -
>>> # ds.quads((None,None,None,"http://www.example.com/gr"))
>>> # would have been accepted, too
>>>
>>> # graph names in the dataset can be queried:
>>> for c in ds.graphs():  
...     print(c)  # doctest:
DEFAULT
http://www.example.com/gr
>>> # A graph can be created without specifying a name; a skolemized genid
>>> # is created on the fly
>>> h = ds.graph()
>>> for c in ds.graphs():  
...     print(c)  
DEFAULT
https://rdflib.github.io/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
>>> for c in ds.graphs(empty=False):  
...     print(c)  
DEFAULT
http://www.example.com/gr
>>>
>>> # a graph can also be removed from a dataset via ds.remove_graph(g)

New in version 4.0.

Parameters:
__getstate__()[source]
Return type:

Tuple[Store, IdentifiedNode, Graph, bool]

__init__(store='default', default_union=False, default_graph_base=None)[source]
Parameters:
__iter__()[source]

Iterates over all quads in the store

Return type:

Generator[Tuple[Node, Node, Node, Optional[IdentifiedNode]], None, None]

__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Dataset], Tuple[Store, bool]]

__setstate__(state)[source]
Parameters:

state (Tuple[Store, IdentifiedNode, Graph, bool]) –

Return type:

None

__str__()[source]

Return str(self).

Return type:

str

add_graph(g)[source]

alias of graph for consistency

Parameters:

g (Union[IdentifiedNode, Graph, str, None]) –

Return type:

Graph

contexts(triple=None)[source]

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

default_context: Graph
graph(identifier=None, base=None)[source]
Parameters:
Return type:

Graph

graphs(triple=None)

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse an RDF source adding the resulting triples to the Graph.

See rdflib.graph.Graph.parse() for documentation on arguments.

The source is specified using one of source, location, file or data.

If the source is in a format that does not support named graphs it’s triples will be added to the default graph (i.e. Dataset.default_context).

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Changed in 7.0: The publicID argument is no longer used as the identifier (i.e. name) of the default graph as was the case before version 7.0. In the case of sources that do not support named graphs, the publicID parameter will also not be used as the name for the graph that the data is loaded into, and instead the triples from sources that do not support named graphs will be loaded into the default graph (i.e. ConjunctionGraph.default_context).

Parameters:
Return type:

Graph

quads(quad=None)[source]

Iterate over all the quads in the entire conjunctive graph

Parameters:

quad (Union[Tuple[Optional[Node], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], Optional[Node], Optional[Graph]], None]) –

Return type:

Generator[Tuple[Node, Node, Node, Optional[IdentifiedNode]], None, None]

remove_graph(g)[source]
Parameters:
Return type:

TypeVar(_DatasetT, bound= Dataset)

class rdflib.graph.Graph(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]

Bases: Node

An RDF Graph

The constructor accepts one argument, the “store” that will be used to store the graph data (see the “store” package for stores currently shipped with rdflib).

Stores can be context-aware or unaware. Unaware stores take up (some) less space but cannot support features that require context, such as true merging/demerging of sub-graphs and provenance.

Even if used with a context-aware store, Graph will only expose the quads which belong to the default graph. To access the rest of the data, ConjunctiveGraph or Dataset classes can be used instead.

The Graph constructor can take an identifier which identifies the Graph by name. If none is given, the graph is assigned a BNode for its identifier.

For more on named graphs, see: http://www.w3.org/2004/03/trix/

Parameters:
__add__(other)[source]

Set-theoretic union BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__and__(other)

Set-theoretic intersection. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__cmp__(other)[source]
Return type:

int

__contains__(triple)[source]

Support for ‘triple in graph’ syntax

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.graph', '__doc__': 'An RDF Graph\n\n    The constructor accepts one argument, the "store"\n    that will be used to store the graph data (see the "store"\n    package for stores currently shipped with rdflib).\n\n    Stores can be context-aware or unaware.  Unaware stores take up\n    (some) less space but cannot support features that require\n    context, such as true merging/demerging of sub-graphs and\n    provenance.\n\n    Even if used with a context-aware store, Graph will only expose the quads which\n    belong to the default graph. To access the rest of the data, `ConjunctiveGraph` or\n    `Dataset` classes can be used instead.\n\n    The Graph constructor can take an identifier which identifies the Graph\n    by name.  If none is given, the graph is assigned a BNode for its\n    identifier.\n\n    For more on named graphs, see: http://www.w3.org/2004/03/trix/\n    ', '__init__': <function Graph.__init__>, 'store': <property object>, 'identifier': <property object>, 'namespace_manager': <property object>, '__repr__': <function Graph.__repr__>, '__str__': <function Graph.__str__>, 'toPython': <function Graph.toPython>, 'destroy': <function Graph.destroy>, 'commit': <function Graph.commit>, 'rollback': <function Graph.rollback>, 'open': <function Graph.open>, 'close': <function Graph.close>, 'add': <function Graph.add>, 'addN': <function Graph.addN>, 'remove': <function Graph.remove>, 'triples': <function Graph.triples>, '__getitem__': <function Graph.__getitem__>, '__len__': <function Graph.__len__>, '__iter__': <function Graph.__iter__>, '__contains__': <function Graph.__contains__>, '__hash__': <function Graph.__hash__>, '__cmp__': <function Graph.__cmp__>, '__eq__': <function Graph.__eq__>, '__lt__': <function Graph.__lt__>, '__le__': <function Graph.__le__>, '__gt__': <function Graph.__gt__>, '__ge__': <function Graph.__ge__>, '__iadd__': <function Graph.__iadd__>, '__isub__': <function Graph.__isub__>, '__add__': <function Graph.__add__>, '__mul__': <function Graph.__mul__>, '__sub__': <function Graph.__sub__>, '__xor__': <function Graph.__xor__>, '__or__': <function Graph.__add__>, '__and__': <function Graph.__mul__>, 'set': <function Graph.set>, 'subjects': <function Graph.subjects>, 'predicates': <function Graph.predicates>, 'objects': <function Graph.objects>, 'subject_predicates': <function Graph.subject_predicates>, 'subject_objects': <function Graph.subject_objects>, 'predicate_objects': <function Graph.predicate_objects>, 'triples_choices': <function Graph.triples_choices>, 'value': <function Graph.value>, 'items': <function Graph.items>, 'transitiveClosure': <function Graph.transitiveClosure>, 'transitive_objects': <function Graph.transitive_objects>, 'transitive_subjects': <function Graph.transitive_subjects>, 'qname': <function Graph.qname>, 'compute_qname': <function Graph.compute_qname>, 'bind': <function Graph.bind>, 'namespaces': <function Graph.namespaces>, 'absolutize': <function Graph.absolutize>, 'serialize': <function Graph.serialize>, 'print': <function Graph.print>, 'parse': <function Graph.parse>, 'query': <function Graph.query>, 'update': <function Graph.update>, 'n3': <function Graph.n3>, '__reduce__': <function Graph.__reduce__>, 'isomorphic': <function Graph.isomorphic>, 'connected': <function Graph.connected>, 'all_nodes': <function Graph.all_nodes>, 'collection': <function Graph.collection>, 'resource': <function Graph.resource>, '_process_skolem_tuples': <function Graph._process_skolem_tuples>, 'skolemize': <function Graph.skolemize>, 'de_skolemize': <function Graph.de_skolemize>, 'cbd': <function Graph.cbd>, '__dict__': <attribute '__dict__' of 'Graph' objects>, '__weakref__': <attribute '__weakref__' of 'Graph' objects>, '__annotations__': {'__identifier': '_ContextIdentifierType', '__store': 'Store'}})
__eq__(other)[source]

Return self==value.

Return type:

bool

__ge__(other)[source]

Return self>=value.

Parameters:

other (Graph) –

Return type:

bool

__getitem__(item)[source]

A graph can be “sliced” as a shortcut for the triples method The python slice syntax is (ab)used for specifying triples. A generator over matches is returned, the returned tuples include only the parts not given

>>> import rdflib
>>> g = rdflib.Graph()
>>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
[(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]
>>> list(g[:namespace.RDFS.label]) # all label triples
[(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]
>>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
[(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]

Combined with SPARQL paths, more complex queries can be written concisely:

Name of all Bobs friends:

g[bob : FOAF.knows/FOAF.name ]

Some label for Bob:

g[bob : DC.title|FOAF.name|RDFS.label]

All friends and friends of friends of Bob

g[bob : FOAF.knows * “+”]

etc.

New in version 4.0.

__gt__(other)[source]

Return self>value.

Return type:

bool

__hash__()[source]

Return hash(self).

Return type:

int

__iadd__(other)[source]

Add all triples in Graph other to Graph. BNode IDs are not changed.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

__init__(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]
Parameters:
__isub__(other)[source]

Subtract all triples in Graph other from Graph. BNode IDs are not changed.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

__iter__()[source]

Iterates over all triples in the store

Return type:

Generator[Tuple[Node, Node, Node], None, None]

__le__(other)[source]

Return self<=value.

Parameters:

other (Graph) –

Return type:

bool

__len__()[source]

Returns the number of triples in the graph

If context is specified then the number of triples in the context is returned instead.

Return type:

int

__lt__(other)[source]

Return self<value.

Return type:

bool

__module__ = 'rdflib.graph'
__mul__(other)[source]

Set-theoretic intersection. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__or__(other)

Set-theoretic union BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]

__repr__()[source]

Return repr(self).

Return type:

str

__str__()[source]

Return str(self).

Return type:

str

__sub__(other)[source]

Set-theoretic difference. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__weakref__

list of weak references to the object (if defined)

__xor__(other)[source]

Set-theoretic XOR. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

absolutize(uri, defrag=1)[source]

Turn uri into an absolute URI if it’s not one already

Parameters:
  • uri (str) –

  • defrag (int) –

Return type:

URIRef

add(triple)[source]

Add a triple with self as context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

addN(quads)[source]

Add a sequence of triple with context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

all_nodes()[source]
Return type:

Set[Node]

bind(prefix, namespace, override=True, replace=False)[source]

Bind prefix to namespace

If override is True will bind namespace to given prefix even if namespace was already bound to a different prefix.

if replace, replace any existing prefix with the new namespace

for example: graph.bind(“foaf”, “http://xmlns.com/foaf/0.1/”)

Parameters:
Return type:

None

cbd(resource, *, target_graph=None)[source]

Retrieves the Concise Bounded Description of a Resource from a Graph

Concise Bounded Description (CBD) is defined in [1] as:

Given a particular node (the starting node) in a particular RDF graph (the source graph), a subgraph of that particular graph, taken to comprise a concise bounded description of the resource denoted by the starting node, can be identified as follows:

  1. Include in the subgraph all statements in the source graph where the subject of the statement is the

    starting node;

  2. Recursively, for all statements identified in the subgraph thus far having a blank node object, include

    in the subgraph all statements in the source graph where the subject of the statement is the blank node in question and which are not already included in the subgraph.

  3. Recursively, for all statements included in the subgraph thus far, for all reifications of each statement

    in the source graph, include the concise bounded description beginning from the rdf:Statement node of each reification.

This results in a subgraph where the object nodes are either URI references, literals, or blank nodes not serving as the subject of any statement in the graph.

[1] https://www.w3.org/Submission/CBD/

Parameters:
  • resource (Node) – a URIRef object, of the Resource for queried for

  • target_graph (Optional[Graph]) – Optionally, a graph to add the CBD to; otherwise, a new graph is created for the CBD

Return type:

Graph

Returns:

a Graph, subgraph of self if no graph was provided otherwise the provided graph

close(commit_pending_transaction=False)[source]

Close the graph store

Might be necessary for stores that require closing a connection to a database or releasing some resource.

Parameters:

commit_pending_transaction (bool) –

Return type:

None

collection(identifier)[source]

Create a new Collection instance.

Parameters:

  • identifier: a URIRef or BNode instance.

Example:

>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> collection = graph.collection(uri)
>>> assert isinstance(collection, Collection)
>>> assert collection.uri is uri
>>> assert collection.graph is graph
>>> collection += [ Literal(1), Literal(2) ]
Parameters:

identifier (Node) –

Return type:

Collection

commit()[source]

Commits active transactions

Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

compute_qname(uri, generate=True)[source]
Parameters:
  • uri (str) –

  • generate (bool) –

Return type:

Tuple[str, URIRef, str]

connected()[source]

Check if the Graph is connected

The Graph is considered undirectional.

Performs a search on the Graph, starting from a random node. Then iteratively goes depth-first through the triplets where the node is subject and object. Return True if all nodes have been visited and False if it cannot continue and there are still unvisited nodes left.

Return type:

bool

de_skolemize(new_graph=None, uriref=None)[source]
Parameters:
Return type:

Graph

destroy(configuration)[source]

Destroy the store identified by configuration if supported

Parameters:
  • self (TypeVar(_GraphT, bound= Graph)) –

  • configuration (str) –

Return type:

TypeVar(_GraphT, bound= Graph)

property identifier: IdentifiedNode
isomorphic(other)[source]

does a very basic check if these graphs are the same If no BNodes are involved, this is accurate.

See rdflib.compare for a correct implementation of isomorphism checks

Parameters:

other (Graph) –

Return type:

bool

items(list)[source]

Generator over all items in the resource specified by list

list is an RDF collection.

Parameters:

list (Node) –

Return type:

Generator[Node, None, None]

n3()[source]

Return an n3 identifier for the Graph

Return type:

str

property namespace_manager: NamespaceManager

this graph’s namespace-manager

namespaces()[source]

Generator over all the prefix, namespace tuples

Return type:

Generator[Tuple[str, URIRef], None, None]

objects(subject=None, predicate=None, unique=False)[source]

A generator of (optionally unique) objects with the given subject and predicate

Parameters:
Return type:

Generator[Node, None, None]

open(configuration, create=False)[source]

Open the graph store

Might be necessary for stores that require opening a connection to a database or acquiring some resource.

Parameters:
  • configuration (str) –

  • create (bool) –

Return type:

Optional[int]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse an RDF source adding the resulting triples to the Graph.

The source is specified using one of source, location, file or data.

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Parameters:
  • source (Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath, None]) – An InputSource, file-like object, Path like object, or string. In the case of a string the string is the location of the source.

  • location (Optional[str]) – A string indicating the relative or absolute URL of the source. Graph’s absolutize method is used if a relative location is specified.

  • file (Union[BinaryIO, TextIO, None]) – A file-like object.

  • data (Union[str, bytes, None]) – A string containing the data to be parsed.

  • format (Optional[str]) – Used if format can not be determined from source, e.g. file extension or Media Type. Defaults to text/turtle. Format support can be extended with plugins, but “xml”, “n3” (use for turtle), “nt” & “trix” are built in.

  • publicID (Optional[str]) – the logical URI to use as the document base. If None specified the document location is used (at least in the case where there is a document location). This is used as the base URI when resolving relative URIs in the source document, as defined in IETF RFC 3986, given the source document does not define a base URI.

Return type:

Graph

Returns:

self, i.e. the Graph instance.

Examples:

>>> my_data = '''
... <rdf:RDF
...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... >
...   <rdf:Description>
...     <rdfs:label>Example</rdfs:label>
...     <rdfs:comment>This is really just an example.</rdfs:comment>
...   </rdf:Description>
... </rdf:RDF>
... '''
>>> import os, tempfile
>>> fd, file_name = tempfile.mkstemp()
>>> f = os.fdopen(fd, "w")
>>> dummy = f.write(my_data)  # Returns num bytes written
>>> f.close()
>>> g = Graph()
>>> result = g.parse(data=my_data, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> result = g.parse(location=file_name, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> with open(file_name, "r") as f:
...     result = g.parse(f, format="application/rdf+xml")
>>> len(g)
2
>>> os.remove(file_name)
>>> # default turtle parsing
>>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
>>> len(g)
3
Parameters:

args (Any) –

predicate_objects(subject=None, unique=False)[source]

A generator of (optionally unique) (predicate, object) tuples for the given subject

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

predicates(subject=None, object=None, unique=False)[source]

A generator of (optionally unique) predicates with the given subject and object

Parameters:
Return type:

Generator[Node, None, None]

print(format='turtle', encoding='utf-8', out=None)[source]
Parameters:
Return type:

None

qname(uri)[source]
Parameters:

uri (str) –

Return type:

str

query(query_object, processor='sparql', result='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]

Query this graph.

A type of ‘prepared queries’ can be realised by providing initial variable bindings with initBindings

Initial namespaces are used to resolve prefixes used in the query, if none are given, the namespaces from the graph’s namespace manager are used.

Caution

This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in SERVICE directives.

When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Returntype:

Result

Parameters:
Return type:

Result

remove(triple)[source]

Remove a triple from the graph

If the triple does not provide a context attribute, removes the triple from all contexts.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

resource(identifier)[source]

Create a new Resource instance.

Parameters:

  • identifier: a URIRef or BNode instance.

Example:

>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> resource = graph.resource(uri)
>>> assert isinstance(resource, Resource)
>>> assert resource.identifier is uri
>>> assert resource.graph is graph
Parameters:

identifier (Union[Node, str]) –

Return type:

Resource

rollback()[source]

Rollback active transactions

Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

serialize(destination=None, format='turtle', base=None, encoding=None, **args)[source]

Serialize the graph.

Parameters:
  • destination (Union[str, PurePath, IO[bytes], None]) – The destination to serialize the graph to. This can be a path as a str or PurePath object, or it can be a IO[bytes] like object. If this parameter is not supplied the serialized graph will be returned.

  • format (str) – The format that the output should be written in. This value references a Serializer plugin. Format support can be extended with plugins, but "xml", "n3", "turtle", "nt", "pretty-xml", "trix", "trig", "nquads", "json-ld" and "hext" are built in. Defaults to "turtle".

  • base (Optional[str]) – The base IRI for formats that support it. For the turtle format this will be used as the @base directive.

  • encoding (Optional[str]) – Encoding of output.

  • args (Any) – Additional arguments to pass to the Serializer that will be used.

  • self (TypeVar(_GraphT, bound= Graph)) –

Returns:

The serialized graph if destination is None. The serialized graph is returned as str if no encoding is specified, and as bytes if an encoding is specified.

Return type:

bytes if destination is None and encoding is not None.

Return type:

str if destination is None and encoding is None.

Returns:

self (i.e. the Graph instance) if destination is not None.

Return type:

Graph if destination is not None.

set(triple)[source]

Convenience method to update the value of object

Remove any existing triples for subject and predicate before adding (subject, predicate, object).

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

skolemize(new_graph=None, bnode=None, authority=None, basepath=None)[source]
Parameters:
Return type:

Graph

property store: Store
subject_objects(predicate=None, unique=False)[source]

A generator of (optionally unique) (subject, object) tuples for the given predicate

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

subject_predicates(object=None, unique=False)[source]

A generator of (optionally unique) (subject, predicate) tuples for the given object

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

subjects(predicate=None, object=None, unique=False)[source]

A generator of (optionally unique) subjects with the given predicate and object

Parameters:
Return type:

Generator[Node, None, None]

toPython()[source]
Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

transitiveClosure(func, arg, seen=None)[source]

Generates transitive closure of a user-defined function against the graph

>>> from rdflib.collection import Collection
>>> g=Graph()
>>> a=BNode("foo")
>>> b=BNode("bar")
>>> c=BNode("baz")
>>> g.add((a,RDF.first,RDF.type)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((a,RDF.rest,b)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b,RDF.first,namespace.RDFS.label)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b,RDF.rest,c)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c,RDF.first,namespace.RDFS.comment)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c,RDF.rest,RDF.nil)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> def topList(node,g):
...    for s in g.subjects(RDF.rest, node):
...       yield s
>>> def reverseList(node,g):
...    for f in g.objects(node, RDF.first):
...       print(f)
...    for s in g.subjects(RDF.rest, node):
...       yield s
>>> [rt for rt in g.transitiveClosure(
...     topList,RDF.nil)] 
[rdflib.term.BNode('baz'),
 rdflib.term.BNode('bar'),
 rdflib.term.BNode('foo')]
>>> [rt for rt in g.transitiveClosure(
...     reverseList,RDF.nil)] 
http://www.w3.org/2000/01/rdf-schema#comment
http://www.w3.org/2000/01/rdf-schema#label
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
[rdflib.term.BNode('baz'),
 rdflib.term.BNode('bar'),
 rdflib.term.BNode('foo')]
Parameters:
transitive_objects(subject, predicate, remember=None)[source]

Transitively generate objects for the predicate relationship

Generated objects belong to the depth first transitive closure of the predicate relationship starting at subject.

Parameters:
Return type:

Generator[Optional[Node], None, None]

transitive_subjects(predicate, object, remember=None)[source]

Transitively generate subjects for the predicate relationship

Generated subjects belong to the depth first transitive closure of the predicate relationship starting at object.

Parameters:
Return type:

Generator[Optional[Node], None, None]

triples(triple)[source]

Generator over the triple store

Returns triples that match the given triple pattern. If triple pattern does not provide a context, all contexts will be searched.

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

triples_choices(triple, context=None)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node, Node], None, None]

update(update_object, processor='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]

Update this graph with the given update query.

Caution

This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in SERVICE directives.

When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Parameters:
Return type:

None

value(subject=None, predicate=rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#value'), object=None, default=None, any=True)[source]

Get a value for a pair of two criteria

Exactly one of subject, predicate, object must be None. Useful if one knows that there may only be one value.

It is one of those situations that occur a lot, hence this ‘macro’ like utility

Parameters: subject, predicate, object – exactly one must be None default – value to be returned if no values found any – if True, return any value in the case there is more than one, else, raise UniquenessError

Parameters:
Return type:

Optional[Node]

exception rdflib.graph.ModificationException[source]

Bases: Exception

__init__()[source]
__module__ = 'rdflib.graph'
__str__()[source]

Return str(self).

Return type:

str

__weakref__

list of weak references to the object (if defined)

class rdflib.graph.QuotedGraph(store, identifier)[source]

Bases: Graph

Quoted Graphs are intended to implement Notation 3 formulae. They are associated with a required identifier that the N3 parser must provide in order to maintain consistent formulae identification for scenarios such as implication and other such processing.

Parameters:
__init__(store, identifier)[source]
Parameters:
__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]

__str__()[source]

Return str(self).

Return type:

str

add(triple)[source]

Add a triple with self as context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

addN(quads)[source]

Add a sequence of triple with context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

n3()[source]

Return an n3 identifier for the Graph

Return type:

str

class rdflib.graph.ReadOnlyGraphAggregate(graphs, store='default')[source]

Bases: ConjunctiveGraph

Utility class for treating a set of graphs as a single graph

Only read operations are supported (hence the name). Essentially a ConjunctiveGraph over an explicit subset of the entire store.

Parameters:
__cmp__(other)[source]
Return type:

int

__contains__(triple_or_quad)[source]

Support for ‘triple/quad in graph’ syntax

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]], Tuple[Optional[Node], Union[Path, Node, None], Optional[Node], Optional[Graph]]]) –

Return type:

bool

__hash__()[source]

Return hash(self).

Return type:

NoReturn

__iadd__(other)[source]

Add all triples in Graph other to Graph. BNode IDs are not changed.

Parameters:
Return type:

NoReturn

__init__(graphs, store='default')[source]
Parameters:
__isub__(other)[source]

Subtract all triples in Graph other from Graph. BNode IDs are not changed.

Parameters:
Return type:

NoReturn

__len__()[source]

Number of triples in the entire conjunctive graph

Return type:

int

__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

NoReturn

__repr__()[source]

Return repr(self).

Return type:

str

absolutize(uri, defrag=1)[source]

Turn uri into an absolute URI if it’s not one already

Parameters:
  • uri (str) –

  • defrag (int) –

Return type:

NoReturn

add(triple)[source]

Add a triple or quad to the store.

if a triple is given it is added to the default context

Parameters:

triple (Union[Tuple[Node, Node, Node], Tuple[Node, Node, Node, Optional[Graph]]]) –

Return type:

NoReturn

addN(quads)[source]

Add a sequence of triples with context

Parameters:

quads (Iterable[Tuple[Node, Node, Node, Graph]]) –

Return type:

NoReturn

bind(prefix, namespace, override=True)[source]

Bind prefix to namespace

If override is True will bind namespace to given prefix even if namespace was already bound to a different prefix.

if replace, replace any existing prefix with the new namespace

for example: graph.bind(“foaf”, “http://xmlns.com/foaf/0.1/”)

Parameters:
Return type:

NoReturn

close()[source]

Close the graph store

Might be necessary for stores that require closing a connection to a database or releasing some resource.

Return type:

None

commit()[source]

Commits active transactions

Return type:

NoReturn

compute_qname(uri, generate=True)[source]
Parameters:
  • uri (str) –

  • generate (bool) –

Return type:

Tuple[str, URIRef, str]

default_context: Graph
destroy(configuration)[source]

Destroy the store identified by configuration if supported

Parameters:

configuration (str) –

Return type:

NoReturn

n3()[source]

Return an n3 identifier for the Graph

Return type:

NoReturn

namespaces()[source]

Generator over all the prefix, namespace tuples

Return type:

Generator[Tuple[str, URIRef], None, None]

open(configuration, create=False)[source]

Open the graph store

Might be necessary for stores that require opening a connection to a database or acquiring some resource.

Parameters:
  • configuration (str) –

  • create (bool) –

Return type:

None

parse(source, publicID=None, format=None, **args)[source]

Parse source adding the resulting triples to its own context (sub graph of this graph).

See rdflib.graph.Graph.parse() for documentation on arguments.

If the source is in a format that does not support named graphs it’s triples will be added to the default graph (i.e. Dataset.default_context).

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root context.

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Changed in 7.0: The publicID argument is no longer used as the identifier (i.e. name) of the default graph as was the case before version 7.0. In the case of sources that do not support named graphs, the publicID parameter will also not be used as the name for the graph that the data is loaded into, and instead the triples from sources that do not support named graphs will be loaded into the default graph (i.e. ConjunctionGraph.default_context).

Parameters:
Return type:

NoReturn

qname(uri)[source]
Parameters:

uri (str) –

Return type:

str

quads(triple_or_quad)[source]

Iterate over all the quads in the entire aggregate graph

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]], Tuple[Optional[Node], Union[Path, Node, None], Optional[Node], Optional[Graph]]]) –

Return type:

Generator[Tuple[Node, Union[Path, Node], Node, Graph], None, None]

remove(triple)[source]

Removes a triple or quads

if a triple is given it is removed from all contexts

a quad is removed from the given context only

Parameters:

triple (Union[Tuple[Node, Node, Node], Tuple[Node, Node, Node, Optional[Graph]]]) –

Return type:

NoReturn

rollback()[source]

Rollback active transactions

Return type:

NoReturn

triples(triple)[source]

Iterate over all the triples in the entire conjunctive graph

For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

triples_choices(triple, context=None)[source]

Iterate over all the triples in the entire conjunctive graph

Parameters:
Return type:

Generator[Tuple[Node, Node, Node], None, None]

class rdflib.graph.Seq(graph, subject)[source]

Bases: object

Wrapper around an RDF Seq resource

It implements a container type in Python with the order of the items returned corresponding to the Seq content. It is based on the natural ordering of the predicate names _1, _2, _3, etc, which is the ‘implementation’ of a sequence in RDF terms.

Parameters:
__dict__ = mappingproxy({'__module__': 'rdflib.graph', '__doc__': "Wrapper around an RDF Seq resource\n\n    It implements a container type in Python with the order of the items\n    returned corresponding to the Seq content. It is based on the natural\n    ordering of the predicate names _1, _2, _3, etc, which is the\n    'implementation' of a sequence in RDF terms.\n    ", '__init__': <function Seq.__init__>, 'toPython': <function Seq.toPython>, '__iter__': <function Seq.__iter__>, '__len__': <function Seq.__len__>, '__getitem__': <function Seq.__getitem__>, '__dict__': <attribute '__dict__' of 'Seq' objects>, '__weakref__': <attribute '__weakref__' of 'Seq' objects>, '__annotations__': {'_list': 'List[Tuple[int, _ObjectType]]'}})
__getitem__(index)[source]

Item given by index from the Seq

Return type:

Node

__init__(graph, subject)[source]

Parameters:

  • graph:

    the graph containing the Seq

  • subject:

    the subject of a Seq. Note that the init does not check whether this is a Seq, this is done in whoever creates this instance!

Parameters:
__iter__()[source]

Generator over the items in the Seq

Return type:

Generator[Node, None, None]

__len__()[source]

Length of the Seq

Return type:

int

__module__ = 'rdflib.graph'
__weakref__

list of weak references to the object (if defined)

toPython()[source]
Return type:

Seq

exception rdflib.graph.UnSupportedAggregateOperation[source]

Bases: Exception

__init__()[source]
__module__ = 'rdflib.graph'
__str__()[source]

Return str(self).

Return type:

str

__weakref__

list of weak references to the object (if defined)

rdflib.parser module

Parser plugin interface.

This module defines the parser plugin interface and contains other related parser support code.

The module is mainly useful for those wanting to write a parser that can plugin to rdflib. If you are wanting to invoke a parser you likely want to do so through the Graph class parse method.

class rdflib.parser.FileInputSource(file)[source]

Bases: InputSource

Parameters:

file (Union[BinaryIO, TextIO, TextIOBase, RawIOBase, BufferedIOBase]) –

__init__(file)[source]
Parameters:

file (Union[BinaryIO, TextIO, TextIOBase, RawIOBase, BufferedIOBase]) –

__module__ = 'rdflib.parser'
__repr__()[source]

Return repr(self).

Return type:

str

class rdflib.parser.InputSource(system_id=None)[source]

Bases: InputSource

TODO:

Parameters:

system_id (Optional[str]) –

__init__(system_id=None)[source]
Parameters:

system_id (Optional[str]) –

__module__ = 'rdflib.parser'
close()[source]
Return type:

None

class rdflib.parser.Parser[source]

Bases: object

__init__()[source]
__module__ = 'rdflib.parser'
__slots__ = ()
parse(source, sink)[source]
Parameters:
Return type:

None

class rdflib.parser.PythonInputSource(data, system_id=None)[source]

Bases: InputSource

Constructs an RDFLib Parser InputSource from a Python data structure, for example, loaded from JSON with json.load or json.loads:

>>> import json
>>> as_string = """{
...   "@context" : {"ex" : "http://example.com/ns#"},
...   "@graph": [{"@type": "ex:item", "@id": "#example"}]
... }"""
>>> as_python = json.loads(as_string)
>>> source = create_input_source(data=as_python)
>>> isinstance(source, PythonInputSource)
True
Parameters:
__init__(data, system_id=None)[source]
Parameters:
__module__ = 'rdflib.parser'
close()[source]
Return type:

None

content_type: Optional[str]
getPublicId()[source]

Returns the public identifier of this InputSource.

Return type:

Optional[str]

getSystemId()[source]

Returns the system identifier of this InputSource.

Return type:

Optional[str]

setPublicId(public_id)[source]

Sets the public identifier of this InputSource.

Parameters:

public_id (Optional[str]) –

Return type:

None

setSystemId(system_id)[source]

Sets the system identifier of this InputSource.

Parameters:

system_id (Optional[str]) –

Return type:

None

class rdflib.parser.StringInputSource(value, encoding='utf-8', system_id=None)[source]

Bases: InputSource

Constructs an RDFLib Parser InputSource from a Python String or Bytes

Parameters:
__init__(value, encoding='utf-8', system_id=None)[source]
Parameters:
__module__ = 'rdflib.parser'
content_type: Optional[str]
class rdflib.parser.URLInputSource(system_id=None, format=None)[source]

Bases: InputSource

Constructs an RDFLib Parser InputSource from a URL to read it from the Web.

Parameters:
__annotations__ = {'links': 'List[str]'}
__init__(system_id=None, format=None)[source]
Parameters:
__module__ = 'rdflib.parser'
__repr__()[source]

Return repr(self).

Return type:

str

get_alternates(type_=None)[source]
Parameters:

type_ (Optional[str]) –

Return type:

List[str]

Parameters:

response (addinfourl) –

Return type:

List[str]

classmethod getallmatchingheaders(message, name)[source]
Parameters:

message (Message) –

Return type:

List[str]

rdflib.paths module

This module implements the SPARQL 1.1 Property path operators, as defined in:

http://www.w3.org/TR/sparql11-query/#propertypaths

In SPARQL the syntax is as follows:

Syntax

Matches

iri

An IRI. A path of length one.

^elt

Inverse path (object to subject).

elt1 / elt2

A sequence path of elt1 followed by elt2.

elt1 | elt2

A alternative path of elt1 or elt2 (all possibilities are tried).

elt*

A path that connects the subject and object of the path by zero or more matches of elt.

elt+

A path that connects the subject and object of the path by one or more matches of elt.

elt?

A path that connects the subject and object of the path by zero or one matches of elt.

!iri or !(iri1| … |irin)

Negated property set. An IRI which is not one of iri1…irin. !iri is short for !(iri).

!^iri or !(^iri1| …|^irin)

Negated property set where the excluded matches are based on reversed path. That is, not one of iri1…irin as reverse paths. !^iri is short for !(^iri).

!(iri1| …|irij|^irij+1|… |^irin)|

A combination of forward and reverse properties in a negated property set.

(elt)

A group path elt, brackets control precedence.

This module is used internally by the SPARQL engine, but the property paths can also be used to query RDFLib Graphs directly.

Where possible the SPARQL syntax is mapped to Python operators, and property path objects can be constructed from existing URIRefs.

>>> from rdflib import Graph, Namespace
>>> from rdflib.namespace import FOAF
>>> ~FOAF.knows
Path(~http://xmlns.com/foaf/0.1/knows)
>>> FOAF.knows/FOAF.name
Path(http://xmlns.com/foaf/0.1/knows / http://xmlns.com/foaf/0.1/name)
>>> FOAF.name|FOAF.givenName
Path(http://xmlns.com/foaf/0.1/name | http://xmlns.com/foaf/0.1/givenName)

Modifiers (?, *, +) are done using * (the multiplication operator) and the strings ‘*’, ‘?’, ‘+’, also defined as constants in this file.

>>> FOAF.knows*OneOrMore
Path(http://xmlns.com/foaf/0.1/knows+)

The path objects can also be used with the normal graph methods.

First some example data:

>>> g=Graph()
>>> g=g.parse(data='''
... @prefix : <ex:> .
...
... :a :p1 :c ; :p2 :f .
... :c :p2 :e ; :p3 :g .
... :g :p3 :h ; :p2 :j .
... :h :p3 :a ; :p2 :g .
...
... :q :px :q .
...
... ''', format='n3') 
>>> e = Namespace('ex:')

Graph contains:

>>> (e.a, e.p1/e.p2, e.e) in g
True

Graph generator functions, triples, subjects, objects, etc. :

>>> list(g.objects(e.c, (e.p3*OneOrMore)/e.p2)) 
[rdflib.term.URIRef('ex:j'), rdflib.term.URIRef('ex:g'),
    rdflib.term.URIRef('ex:f')]

A more complete set of tests:

>>> list(eval_path(g, (None, e.p1/e.p2, None)))==[(e.a, e.e)]
True
>>> list(eval_path(g, (e.a, e.p1|e.p2, None)))==[(e.a,e.c), (e.a,e.f)]
True
>>> list(eval_path(g, (e.c, ~e.p1, None))) == [ (e.c, e.a) ]
True
>>> list(eval_path(g, (e.a, e.p1*ZeroOrOne, None))) == [(e.a, e.a), (e.a, e.c)]
True
>>> list(eval_path(g, (e.c, e.p3*OneOrMore, None))) == [
...     (e.c, e.g), (e.c, e.h), (e.c, e.a)]
True
>>> list(eval_path(g, (e.c, e.p3*ZeroOrMore, None))) == [(e.c, e.c),
...     (e.c, e.g), (e.c, e.h), (e.c, e.a)]
True
>>> list(eval_path(g, (e.a, -e.p1, None))) == [(e.a, e.f)]
True
>>> list(eval_path(g, (e.a, -(e.p1|e.p2), None))) == []
True
>>> list(eval_path(g, (e.g, -~e.p2, None))) == [(e.g, e.j)]
True
>>> list(eval_path(g, (e.e, ~(e.p1/e.p2), None))) == [(e.e, e.a)]
True
>>> list(eval_path(g, (e.a, e.p1/e.p3/e.p3, None))) == [(e.a, e.h)]
True
>>> list(eval_path(g, (e.q, e.px*OneOrMore, None)))
[(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))]
>>> list(eval_path(g, (None, e.p1|e.p2, e.c)))
[(rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))]
>>> list(eval_path(g, (None, ~e.p1, e.a))) == [ (e.c, e.a) ]
True
>>> list(eval_path(g, (None, e.p1*ZeroOrOne, e.c))) 
[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:c')),
 (rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))]
>>> list(eval_path(g, (None, e.p3*OneOrMore, e.a))) 
[(rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a'))]
>>> list(eval_path(g, (None, e.p3*ZeroOrMore, e.a))) 
[(rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a'))]
>>> list(eval_path(g, (None, -e.p1, e.f))) == [(e.a, e.f)]
True
>>> list(eval_path(g, (None, -(e.p1|e.p2), e.c))) == []
True
>>> list(eval_path(g, (None, -~e.p2, e.j))) == [(e.g, e.j)]
True
>>> list(eval_path(g, (None, ~(e.p1/e.p2), e.a))) == [(e.e, e.a)]
True
>>> list(eval_path(g, (None, e.p1/e.p3/e.p3, e.h))) == [(e.a, e.h)]
True
>>> list(eval_path(g, (e.q, e.px*OneOrMore, None)))
[(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))]
>>> list(eval_path(g, (e.c, (e.p2|e.p3)*ZeroOrMore, e.j)))
[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:j'))]

No vars specified:

>>> sorted(list(eval_path(g, (None, e.p3*OneOrMore, None)))) 
[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:g')),
 (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:h')),
 (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')),
 (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:h')),
 (rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a'))]
class rdflib.paths.AlternativePath(*args)[source]

Bases: Path

Parameters:

args (Union[Path, URIRef]) –

__init__(*args)[source]
Parameters:

args (Union[Path, URIRef]) –

__module__ = 'rdflib.paths'
__repr__()[source]

Return repr(self).

Return type:

str

eval(graph, subj=None, obj=None)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

class rdflib.paths.InvPath(arg)[source]

Bases: Path

Parameters:

arg (Union[Path, URIRef]) –

__init__(arg)[source]
Parameters:

arg (Union[Path, URIRef]) –

__module__ = 'rdflib.paths'
__repr__()[source]

Return repr(self).

Return type:

str

eval(graph, subj=None, obj=None)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

class rdflib.paths.MulPath(path, mod)[source]

Bases: Path

Parameters:
__init__(path, mod)[source]
Parameters:
__module__ = 'rdflib.paths'
__repr__()[source]

Return repr(self).

Return type:

str

eval(graph, subj=None, obj=None, first=True)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

class rdflib.paths.NegatedPath(arg)[source]

Bases: Path

Parameters:

arg (Union[AlternativePath, InvPath, URIRef]) –

__init__(arg)[source]
Parameters:

arg (Union[AlternativePath, InvPath, URIRef]) –

__module__ = 'rdflib.paths'
__repr__()[source]

Return repr(self).

Return type:

str

eval(graph, subj=None, obj=None)[source]
n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

class rdflib.paths.Path[source]

Bases: object

__annotations__ = {'__invert__': "Callable[['Path'], 'InvPath']", '__mul__': "Callable[['Path', str], 'MulPath']", '__neg__': "Callable[['Path'], 'NegatedPath']", '__or__': "Callable[['Path', Union['URIRef', 'Path']], 'AlternativePath']", '__truediv__': "Callable[['Path', Union['URIRef', 'Path']], 'SequencePath']"}
__dict__ = mappingproxy({'__module__': 'rdflib.paths', '__annotations__': {'__or__': "Callable[['Path', Union['URIRef', 'Path']], 'AlternativePath']", '__invert__': "Callable[['Path'], 'InvPath']", '__neg__': "Callable[['Path'], 'NegatedPath']", '__truediv__': "Callable[['Path', Union['URIRef', 'Path']], 'SequencePath']", '__mul__': "Callable[['Path', str], 'MulPath']"}, 'eval': <function Path.eval>, '__hash__': <function Path.__hash__>, '__eq__': <function Path.__eq__>, '__lt__': <function Path.__lt__>, '__dict__': <attribute '__dict__' of 'Path' objects>, '__weakref__': <attribute '__weakref__' of 'Path' objects>, '__doc__': None, '__gt__': <function _gt_from_lt>, '__le__': <function _le_from_lt>, '__ge__': <function _ge_from_lt>, '__invert__': <function inv_path>, '__neg__': <function neg_path>, '__mul__': <function mul_path>, '__or__': <function path_alternative>, '__truediv__': <function path_sequence>})
__eq__(other)[source]

Return self==value.

__ge__(other, NotImplemented=NotImplemented)

Return a >= b. Computed by @total_ordering from (not a < b).

__gt__(other, NotImplemented=NotImplemented)

Return a > b. Computed by @total_ordering from (not a < b) and (a != b).

__hash__()[source]

Return hash(self).

__invert__()

inverse path

Parameters:

p (Union[URIRef, Path]) –

Return type:

InvPath

__le__(other, NotImplemented=NotImplemented)

Return a <= b. Computed by @total_ordering from (a < b) or (a == b).

__lt__(other)[source]

Return self<value.

Parameters:

other (Any) –

Return type:

bool

__module__ = 'rdflib.paths'
__mul__(mul)

cardinality path

Parameters:
Return type:

MulPath

__neg__()

negated path

Parameters:

p (Union[URIRef, AlternativePath, InvPath]) –

Return type:

NegatedPath

__or__(other)

alternative path

Parameters:
__truediv__(other)

sequence path

Parameters:
__weakref__

list of weak references to the object (if defined)

eval(graph, subj=None, obj=None)[source]
Parameters:
Return type:

Iterator[Tuple[Node, Node]]

class rdflib.paths.PathList(iterable=(), /)[source]

Bases: list

__dict__ = mappingproxy({'__module__': 'rdflib.paths', '__dict__': <attribute '__dict__' of 'PathList' objects>, '__weakref__': <attribute '__weakref__' of 'PathList' objects>, '__doc__': None, '__annotations__': {}})
__module__ = 'rdflib.paths'
__weakref__

list of weak references to the object (if defined)

class rdflib.paths.SequencePath(*args)[source]

Bases: Path

Parameters:

args (Union[Path, URIRef]) –

__init__(*args)[source]
Parameters:

args (Union[Path, URIRef]) –

__module__ = 'rdflib.paths'
__repr__()[source]

Return repr(self).

Return type:

str

eval(graph, subj=None, obj=None)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

rdflib.paths.evalPath(graph, t)[source]
Parameters:
Return type:

Iterator[Tuple[Node, Node]]

rdflib.paths.eval_path(graph, t)[source]
Parameters:
Return type:

Iterator[Tuple[Node, Node]]

rdflib.paths.inv_path(p)[source]

inverse path

Parameters:

p (Union[URIRef, Path]) –

Return type:

InvPath

rdflib.paths.mul_path(p, mul)[source]

cardinality path

Parameters:
Return type:

MulPath

rdflib.paths.neg_path(p)[source]

negated path

Parameters:

p (Union[URIRef, AlternativePath, InvPath]) –

Return type:

NegatedPath

rdflib.paths.path_alternative(self, other)[source]

alternative path

Parameters:
rdflib.paths.path_sequence(self, other)[source]

sequence path

Parameters:

rdflib.plugin module

Plugin support for rdf.

There are a number of plugin points for rdf: parser, serializer, store, query processor, and query result. Plugins can be registered either through setuptools entry_points or by calling rdf.plugin.register directly.

If you have a package that uses a setuptools based setup.py you can add the following to your setup:

entry_points = {
    'rdf.plugins.parser': [
        'nt =     rdf.plugins.parsers.ntriples:NTParser',
        ],
    'rdf.plugins.serializer': [
        'nt =     rdf.plugins.serializers.NTSerializer:NTSerializer',
        ],
    }

See the setuptools dynamic discovery of services and plugins for more information.

class rdflib.plugin.PKGPlugin(name, kind, ep)[source]

Bases: Plugin[PluginT]

Parameters:
  • name (str) –

  • kind (Type[TypeVar(PluginT)]) –

  • ep (EntryPoint) –

__init__(name, kind, ep)[source]
Parameters:
  • name (str) –

  • kind (Type[TypeVar(PluginT)]) –

  • ep (EntryPoint) –

__module__ = 'rdflib.plugin'
__orig_bases__ = (rdflib.plugin.Plugin[~PluginT],)
__parameters__ = (~PluginT,)
getClass()[source]
Return type:

Type[TypeVar(PluginT)]

class rdflib.plugin.Plugin(name, kind, module_path, class_name)[source]

Bases: Generic[PluginT]

Parameters:
__dict__ = mappingproxy({'__module__': 'rdflib.plugin', '__init__': <function Plugin.__init__>, 'getClass': <function Plugin.getClass>, '__orig_bases__': (typing.Generic[~PluginT],), '__dict__': <attribute '__dict__' of 'Plugin' objects>, '__weakref__': <attribute '__weakref__' of 'Plugin' objects>, '__doc__': None, '__parameters__': (~PluginT,), '__annotations__': {'_class': 'Optional[Type[PluginT]]'}})
__init__(name, kind, module_path, class_name)[source]
Parameters:
__module__ = 'rdflib.plugin'
__orig_bases__ = (typing.Generic[~PluginT],)
__parameters__ = (~PluginT,)
__weakref__

list of weak references to the object (if defined)

getClass()[source]
Return type:

Type[TypeVar(PluginT)]

exception rdflib.plugin.PluginException(msg=None)[source]

Bases: Error

Parameters:

msg (Optional[str]) –

__module__ = 'rdflib.plugin'
class rdflib.plugin.PluginT

A generic type variable for plugins

alias of TypeVar(‘PluginT’)

__module__ = 'rdflib.plugin'
rdflib.plugin.get(name, kind)[source]

Return the class for the specified (name, kind). Raises a PluginException if unable to do so.

Parameters:
Return type:

Type[TypeVar(PluginT)]

rdflib.plugin.plugins(name=None, kind=None)[source]

A generator of the plugins.

Pass in name and kind to filter… else leave None to match all.

Parameters:
Return type:

Iterator[Plugin[TypeVar(PluginT)]]

rdflib.plugin.register(name, kind, module_path, class_name)[source]

Register the plugin for (name, kind). The module_path and class_name should be the path to a plugin class.

Parameters:

rdflib.query module

class rdflib.query.EncodeOnlyUnicode(stream)[source]

Bases: object

This is a crappy work-around for http://bugs.python.org/issue11649

Parameters:

stream (BinaryIO) –

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__doc__': '\n    This is a crappy work-around for\n    http://bugs.python.org/issue11649\n\n\n    ', '__init__': <function EncodeOnlyUnicode.__init__>, 'write': <function EncodeOnlyUnicode.write>, '__getattr__': <function EncodeOnlyUnicode.__getattr__>, '__dict__': <attribute '__dict__' of 'EncodeOnlyUnicode' objects>, '__weakref__': <attribute '__weakref__' of 'EncodeOnlyUnicode' objects>, '__annotations__': {}})
__getattr__(name)[source]
Parameters:

name (str) –

Return type:

Any

__init__(stream)[source]
Parameters:

stream (BinaryIO) –

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

write(arg)[source]
class rdflib.query.Processor(graph)[source]

Bases: object

Query plugin interface.

This module is useful for those wanting to write a query processor that can plugin to rdf. If you are wanting to execute a query you likely want to do so through the Graph class query method.

Parameters:

graph (Graph) –

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__doc__': '\n    Query plugin interface.\n\n    This module is useful for those wanting to write a query processor\n    that can plugin to rdf. If you are wanting to execute a query you\n    likely want to do so through the Graph class query method.\n\n    ', '__init__': <function Processor.__init__>, 'query': <function Processor.query>, '__dict__': <attribute '__dict__' of 'Processor' objects>, '__weakref__': <attribute '__weakref__' of 'Processor' objects>, '__annotations__': {}})
__init__(graph)[source]
Parameters:

graph (Graph) –

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

query(strOrQuery, initBindings={}, initNs={}, DEBUG=False)[source]
Parameters:
Return type:

Mapping[str, Any]

class rdflib.query.Result(type_)[source]

Bases: object

A common class for representing query result.

There is a bit of magic here that makes this appear like different Python objects, depending on the type of result.

If the type is “SELECT”, iterating will yield lists of ResultRow objects

If the type is “ASK”, iterating will yield a single bool (or bool(result) will return the same bool)

If the type is “CONSTRUCT” or “DESCRIBE” iterating will yield the triples.

len(result) also works.

Parameters:

type_ (str) –

__bool__()[source]
Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__doc__': '\n    A common class for representing query result.\n\n    There is a bit of magic here that makes this appear like different\n    Python objects, depending on the type of result.\n\n    If the type is "SELECT", iterating will yield lists of ResultRow objects\n\n    If the type is "ASK", iterating will yield a single bool (or\n    bool(result) will return the same bool)\n\n    If the type is "CONSTRUCT" or "DESCRIBE" iterating will yield the\n    triples.\n\n    len(result) also works.\n\n    ', '__init__': <function Result.__init__>, 'bindings': <property object>, 'parse': <staticmethod object>, 'serialize': <function Result.serialize>, '__len__': <function Result.__len__>, '__bool__': <function Result.__bool__>, '__iter__': <function Result.__iter__>, '__getattr__': <function Result.__getattr__>, '__eq__': <function Result.__eq__>, '__dict__': <attribute '__dict__' of 'Result' objects>, '__weakref__': <attribute '__weakref__' of 'Result' objects>, '__hash__': None, '__annotations__': {'vars': "Optional[List['Variable']]", '_bindings': "MutableSequence[Mapping['Variable', 'Identifier']]", '_genbindings': "Optional[Iterator[Mapping['Variable', 'Identifier']]]", 'askAnswer': 'Optional[bool]', 'graph': "Optional['Graph']"}})
__eq__(other)[source]

Return self==value.

Parameters:

other (Any) –

Return type:

bool

__getattr__(name)[source]
Parameters:

name (str) –

Return type:

Any

__hash__ = None
__init__(type_)[source]
Parameters:

type_ (str) –

__iter__()[source]
Return type:

Iterator[Union[Tuple[Node, Node, Node], bool, ResultRow]]

__len__()[source]
Return type:

int

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

property bindings: MutableSequence[Mapping[Variable, Identifier]]

a list of variable bindings as dicts

static parse(source=None, format=None, content_type=None, **kwargs)[source]
Parameters:
Return type:

Result

serialize(destination=None, encoding='utf-8', format='xml', **args)[source]

Serialize the query result.

The format argument determines the Serializer class to use.

Parameters:
  • destination (Union[str, IO, None]) – Path of file output or BufferedIOBase object to write the output to.

  • encoding (str) – Encoding of output.

  • format (str) – One of [‘csv’, ‘json’, ‘txt’, xml’]

  • args (Any) –

Return type:

Optional[bytes]

Returns:

bytes

vars: Optional[List[Variable]]

variables contained in the result.

exception rdflib.query.ResultException[source]

Bases: Exception

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

class rdflib.query.ResultParser[source]

Bases: object

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__init__': <function ResultParser.__init__>, 'parse': <function ResultParser.parse>, '__dict__': <attribute '__dict__' of 'ResultParser' objects>, '__weakref__': <attribute '__weakref__' of 'ResultParser' objects>, '__doc__': None, '__annotations__': {}})
__init__()[source]
__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

parse(source, **kwargs)[source]

return a Result object

Parameters:
  • source (IO) –

  • kwargs (Any) –

Return type:

Result

class rdflib.query.ResultRow(values: Mapping[Variable, Identifier], labels: List[Variable])[source]

Bases: Tuple[Identifier, …]

a single result row allows accessing bindings as attributes or with []

>>> from rdflib import URIRef, Variable
>>> rr=ResultRow({ Variable('a'): URIRef('urn:cake') }, [Variable('a')])
>>> rr[0]
rdflib.term.URIRef(u'urn:cake')
>>> rr[1]
Traceback (most recent call last):
    ...
IndexError: tuple index out of range
>>> rr.a
rdflib.term.URIRef(u'urn:cake')
>>> rr.b
Traceback (most recent call last):
    ...
AttributeError: b
>>> rr['a']
rdflib.term.URIRef(u'urn:cake')
>>> rr['b']
Traceback (most recent call last):
    ...
KeyError: 'b'
>>> rr[Variable('a')]
rdflib.term.URIRef(u'urn:cake')

New in version 4.0.

__annotations__ = {'labels': 'Mapping[str, int]'}
__dict__ = mappingproxy({'__module__': 'rdflib.query', '__annotations__': {'labels': 'Mapping[str, int]'}, '__doc__': "\n    a single result row\n    allows accessing bindings as attributes or with []\n\n    >>> from rdflib import URIRef, Variable\n    >>> rr=ResultRow({ Variable('a'): URIRef('urn:cake') }, [Variable('a')])\n\n    >>> rr[0]\n    rdflib.term.URIRef(u'urn:cake')\n    >>> rr[1]\n    Traceback (most recent call last):\n        ...\n    IndexError: tuple index out of range\n\n    >>> rr.a\n    rdflib.term.URIRef(u'urn:cake')\n    >>> rr.b\n    Traceback (most recent call last):\n        ...\n    AttributeError: b\n\n    >>> rr['a']\n    rdflib.term.URIRef(u'urn:cake')\n    >>> rr['b']\n    Traceback (most recent call last):\n        ...\n    KeyError: 'b'\n\n    >>> rr[Variable('a')]\n    rdflib.term.URIRef(u'urn:cake')\n\n    .. versionadded:: 4.0\n\n    ", '__new__': <staticmethod object>, '__getattr__': <function ResultRow.__getattr__>, '__getitem__': <function ResultRow.__getitem__>, 'get': <function ResultRow.get>, 'asdict': <function ResultRow.asdict>, '__orig_bases__': (typing.Tuple[ForwardRef('Identifier'), ...],), '__dict__': <attribute '__dict__' of 'ResultRow' objects>, '__parameters__': ()})
__getattr__(name)[source]
Parameters:

name (str) –

Return type:

Identifier

__getitem__(name)[source]

Return self[key].

Parameters:

name (Union[str, int, Any]) –

Return type:

Identifier

__module__ = 'rdflib.query'
static __new__(cls, values, labels)[source]
Parameters:
__orig_bases__ = (typing.Tuple[ForwardRef('Identifier'), ...],)
__parameters__ = ()
asdict()[source]
Return type:

Dict[str, Identifier]

get(name, default=None)[source]
Parameters:
Return type:

Optional[Identifier]

labels: Mapping[str, int]
class rdflib.query.ResultSerializer(result)[source]

Bases: object

Parameters:

result (Result) –

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__init__': <function ResultSerializer.__init__>, 'serialize': <function ResultSerializer.serialize>, '__dict__': <attribute '__dict__' of 'ResultSerializer' objects>, '__weakref__': <attribute '__weakref__' of 'ResultSerializer' objects>, '__doc__': None, '__annotations__': {}})
__init__(result)[source]
Parameters:

result (Result) –

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

serialize(stream, encoding='utf-8', **kwargs)[source]

return a string properly serialized

Parameters:
  • stream (IO) –

  • encoding (str) –

  • kwargs (Any) –

Return type:

None

class rdflib.query.UpdateProcessor(graph)[source]

Bases: object

Update plugin interface.

This module is useful for those wanting to write an update processor that can plugin to rdflib. If you are wanting to execute an update statement you likely want to do so through the Graph class update method.

New in version 4.0.

Parameters:

graph (Graph) –

__dict__ = mappingproxy({'__module__': 'rdflib.query', '__doc__': '\n    Update plugin interface.\n\n    This module is useful for those wanting to write an update\n    processor that can plugin to rdflib. If you are wanting to execute\n    an update statement you likely want to do so through the Graph\n    class update method.\n\n    .. versionadded:: 4.0\n\n    ', '__init__': <function UpdateProcessor.__init__>, 'update': <function UpdateProcessor.update>, '__dict__': <attribute '__dict__' of 'UpdateProcessor' objects>, '__weakref__': <attribute '__weakref__' of 'UpdateProcessor' objects>, '__annotations__': {}})
__init__(graph)[source]
Parameters:

graph (Graph) –

__module__ = 'rdflib.query'
__weakref__

list of weak references to the object (if defined)

update(strOrQuery, initBindings={}, initNs={})[source]
Parameters:
Return type:

None

rdflib.resource module

The Resource class wraps a Graph and a resource reference (i.e. a rdflib.term.URIRef or rdflib.term.BNode) to support a resource-oriented way of working with a graph.

It contains methods directly corresponding to those methods of the Graph interface that relate to reading and writing data. The difference is that a Resource also binds a resource identifier, making it possible to work without tracking both the graph and a current subject. This makes for a “resource oriented” style, as compared to the triple orientation of the Graph API.

Resulting generators are also wrapped so that any resource reference values (rdflib.term.URIRef and rdflib.term.BNode) are in turn wrapped as Resources. (Note that this behaviour differs from the corresponding methods in Graph, where no such conversion takes place.)

Basic Usage Scenario

Start by importing things we need and define some namespaces:

>>> from rdflib import *
>>> FOAF = Namespace("http://xmlns.com/foaf/0.1/")
>>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#")

Load some RDF data:

>>> graph = Graph().parse(format='n3', data='''
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... @prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
... @prefix cv: <http://purl.org/captsolo/resume-rdf/0.2/cv#> .
...
... @base <http://example.org/> .
...
... </person/some1#self> a foaf:Person;
...     rdfs:comment "Just a Python & RDF hacker."@en;
...     foaf:depiction </images/person/some1.jpg>;
...     foaf:homepage <http://example.net/>;
...     foaf:name "Some Body" .
...
... </images/person/some1.jpg> a foaf:Image;
...     rdfs:label "some 1"@en;
...     rdfs:comment "Just an image"@en;
...     foaf:thumbnail </images/person/some1-thumb.jpg> .
...
... </images/person/some1-thumb.jpg> a foaf:Image .
...
... [] a cv:CV;
...     cv:aboutPerson </person/some1#self>;
...     cv:hasWorkHistory [ cv:employedIn </#company>;
...             cv:startDate "2009-09-04"^^xsd:date ] .
... ''')

Create a Resource:

>>> person = Resource(
...     graph, URIRef("http://example.org/person/some1#self"))

Retrieve some basic facts:

>>> person.identifier
rdflib.term.URIRef(u'http://example.org/person/some1#self')

>>> person.value(FOAF.name)
rdflib.term.Literal(u'Some Body')

>>> person.value(RDFS.comment)
rdflib.term.Literal(u'Just a Python & RDF hacker.', lang=u'en')

Resources can be sliced (like graphs, but the subject is fixed):

>>> for name in person[FOAF.name]:
...     print(name)
Some Body
>>> person[FOAF.name : Literal("Some Body")]
True

Resources as unicode are represented by their identifiers as unicode:

>>> %(unicode)s(person)  
u'Resource(http://example.org/person/some1#self'

Resource references are also Resources, so you can easily get e.g. a qname for the type of a resource, like:

>>> person.value(RDF.type).qname()
u'foaf:Person'

Or for the predicates of a resource:

>>> sorted(
...     p.qname() for p in person.predicates()
... )  
[u'foaf:depiction', u'foaf:homepage',
 u'foaf:name', u'rdf:type', u'rdfs:comment']

Follow relations and get more data from their Resources as well:

>>> for pic in person.objects(FOAF.depiction):
...     print(pic.identifier)
...     print(pic.value(RDF.type).qname())
...     print(pic.value(FOAF.thumbnail).identifier)
http://example.org/images/person/some1.jpg
foaf:Image
http://example.org/images/person/some1-thumb.jpg

>>> for cv in person.subjects(CV.aboutPerson):
...     work = list(cv.objects(CV.hasWorkHistory))[0]
...     print(work.value(CV.employedIn).identifier)
...     print(work.value(CV.startDate))
http://example.org/#company
2009-09-04

It’s just as easy to work with the predicates of a resource:

>>> for s, p in person.subject_predicates():
...     print(s.value(RDF.type).qname())
...     print(p.qname())
...     for s, o in p.subject_objects():
...         print(s.value(RDF.type).qname())
...         print(o.value(RDF.type).qname())
cv:CV
cv:aboutPerson
cv:CV
foaf:Person

This is useful for e.g. inspection:

>>> thumb_ref = URIRef("http://example.org/images/person/some1-thumb.jpg")
>>> thumb = Resource(graph, thumb_ref)
>>> for p, o in thumb.predicate_objects():
...     print(p.qname())
...     print(o.qname())
rdf:type
foaf:Image

Schema Example

With this artificial schema data:

>>> graph = Graph().parse(format='n3', data='''
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... @prefix owl: <http://www.w3.org/2002/07/owl#> .
... @prefix v: <http://example.org/def/v#> .
...
... v:Artifact a owl:Class .
...
... v:Document a owl:Class;
...     rdfs:subClassOf v:Artifact .
...
... v:Paper a owl:Class;
...     rdfs:subClassOf v:Document .
...
... v:Choice owl:oneOf (v:One v:Other) .
...
... v:Stuff a rdf:Seq; rdf:_1 v:One; rdf:_2 v:Other .
...
... ''')

From this class:

>>> artifact = Resource(graph, URIRef("http://example.org/def/v#Artifact"))

we can get at subclasses:

>>> subclasses = list(artifact.transitive_subjects(RDFS.subClassOf))
>>> [c.qname() for c in subclasses]
[u'v:Artifact', u'v:Document', u'v:Paper']

and superclasses from the last subclass:

>>> [c.qname() for c in subclasses[-1].transitive_objects(RDFS.subClassOf)]
[u'v:Paper', u'v:Document', u'v:Artifact']

Get items from the Choice:

>>> choice = Resource(graph, URIRef("http://example.org/def/v#Choice"))
>>> [it.qname() for it in choice.value(OWL.oneOf).items()]
[u'v:One', u'v:Other']
On add, other resources are auto-unboxed:
>>> paper = Resource(graph, URIRef("http://example.org/def/v#Paper"))
>>> paper.add(RDFS.subClassOf, artifact)
>>> artifact in paper.objects(RDFS.subClassOf) # checks Resource instance
True
>>> (paper._identifier, RDFS.subClassOf, artifact._identifier) in graph
True

Technical Details

Comparison is based on graph and identifier:

>>> g1 = Graph()
>>> t1 = Resource(g1, URIRef("http://example.org/thing"))
>>> t2 = Resource(g1, URIRef("http://example.org/thing"))
>>> t3 = Resource(g1, URIRef("http://example.org/other"))
>>> t4 = Resource(Graph(), URIRef("http://example.org/other"))

>>> t1 is t2
False

>>> t1 == t2
True
>>> t1 != t2
False

>>> t1 == t3
False
>>> t1 != t3
True

>>> t3 != t4
True

>>> t3 < t1 and t1 > t3
True
>>> t1 >= t1 and t1 >= t3
True
>>> t1 <= t1 and t3 <= t1
True

>>> t1 < t1 or t1 < t3 or t3 > t1 or t3 > t3
False

Hash is computed from graph and identifier:

>>> g1 = Graph()
>>> t1 = Resource(g1, URIRef("http://example.org/thing"))

>>> hash(t1) == hash(Resource(g1, URIRef("http://example.org/thing")))
True

>>> hash(t1) == hash(Resource(Graph(), t1.identifier))
False
>>> hash(t1) == hash(Resource(Graph(), URIRef("http://example.org/thing")))
False

The Resource class is suitable as a base class for mapper toolkits. For example, consider this utility for accessing RDF properties via qname-like attributes:

>>> class Item(Resource):
...
...     def __getattr__(self, p):
...         return list(self.objects(self._to_ref(*p.split('_', 1))))
...
...     def _to_ref(self, pfx, name):
...         return URIRef(self._graph.store.namespace(pfx) + name)

It works as follows:

>>> graph = Graph().parse(format='n3', data='''
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... @prefix foaf: <http://xmlns.com/foaf/0.1/> .
...
... @base <http://example.org/> .
... </person/some1#self>
...     foaf:name "Some Body";
...     foaf:depiction </images/person/some1.jpg> .
... </images/person/some1.jpg> rdfs:comment "Just an image"@en .
... ''')

>>> person = Item(graph, URIRef("http://example.org/person/some1#self"))

>>> print(person.foaf_name[0])
Some Body

The mechanism for wrapping references as resources cooperates with subclasses. Therefore, accessing referenced resources automatically creates new Item objects:

>>> isinstance(person.foaf_depiction[0], Item)
True

>>> print(person.foaf_depiction[0].rdfs_comment[0])
Just an image
class rdflib.resource.Resource(graph, subject)[source]

Bases: object

__dict__ = mappingproxy({'__module__': 'rdflib.resource', '__init__': <function Resource.__init__>, 'graph': <property object>, 'identifier': <property object>, '__hash__': <function Resource.__hash__>, '__eq__': <function Resource.__eq__>, '__ne__': <function Resource.__ne__>, '__lt__': <function Resource.__lt__>, '__gt__': <function Resource.__gt__>, '__le__': <function Resource.__le__>, '__ge__': <function Resource.__ge__>, '__unicode__': <function Resource.__unicode__>, 'add': <function Resource.add>, 'remove': <function Resource.remove>, 'set': <function Resource.set>, 'subjects': <function Resource.subjects>, 'predicates': <function Resource.predicates>, 'objects': <function Resource.objects>, 'subject_predicates': <function Resource.subject_predicates>, 'subject_objects': <function Resource.subject_objects>, 'predicate_objects': <function Resource.predicate_objects>, 'value': <function Resource.value>, 'items': <function Resource.items>, 'transitive_objects': <function Resource.transitive_objects>, 'transitive_subjects': <function Resource.transitive_subjects>, 'qname': <function Resource.qname>, '_resource_pairs': <function Resource._resource_pairs>, '_resource_triples': <function Resource._resource_triples>, '_resources': <function Resource._resources>, '_cast': <function Resource._cast>, '__iter__': <function Resource.__iter__>, '__getitem__': <function Resource.__getitem__>, '__setitem__': <function Resource.__setitem__>, '_new': <function Resource._new>, '__str__': <function Resource.__str__>, '__repr__': <function Resource.__repr__>, '__dict__': <attribute '__dict__' of 'Resource' objects>, '__weakref__': <attribute '__weakref__' of 'Resource' objects>, '__doc__': None, '__annotations__': {}})
__eq__(other)[source]

Return self==value.

__ge__(other)[source]

Return self>=value.

__getitem__(item)[source]
__gt__(other)[source]

Return self>value.

__hash__()[source]

Return hash(self).

__init__(graph, subject)[source]
__iter__()[source]
__le__(other)[source]

Return self<=value.

__lt__(other)[source]

Return self<value.

__module__ = 'rdflib.resource'
__ne__(other)[source]

Return self!=value.

__repr__()[source]

Return repr(self).

__setitem__(item, value)[source]
__str__()[source]

Return str(self).

__unicode__()[source]
__weakref__

list of weak references to the object (if defined)

add(p, o)[source]
property graph
property identifier
items()[source]
objects(predicate=None)[source]
predicate_objects()[source]
predicates(o=None)[source]
qname()[source]
remove(p, o=None)[source]
set(p, o)[source]
subject_objects()[source]
subject_predicates()[source]
subjects(predicate=None)[source]
transitive_objects(predicate, remember=None)[source]
transitive_subjects(predicate, remember=None)[source]
value(p=rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#value'), o=None, default=None, any=True)[source]

rdflib.serializer module

class rdflib.serializer.Serializer(store)[source]

Bases: object

Parameters:

store (Graph) –

__dict__ = mappingproxy({'__module__': 'rdflib.serializer', '__init__': <function Serializer.__init__>, 'serialize': <function Serializer.serialize>, 'relativize': <function Serializer.relativize>, '__dict__': <attribute '__dict__' of 'Serializer' objects>, '__weakref__': <attribute '__weakref__' of 'Serializer' objects>, '__doc__': None, '__annotations__': {'store': "'Graph'", 'encoding': 'str', 'base': 'Optional[str]'}})
__init__(store)[source]
Parameters:

store (Graph) –

__module__ = 'rdflib.serializer'
__weakref__

list of weak references to the object (if defined)

relativize(uri)[source]
Parameters:

uri (TypeVar(_StrT, bound= str)) –

Return type:

Union[TypeVar(_StrT, bound= str), URIRef]

serialize(stream, base=None, encoding=None, **args)[source]

Abstract method

Parameters:
Return type:

None

rdflib.store module

class rdflib.store.NodePickler[source]

Bases: object

__dict__ = mappingproxy({'__module__': 'rdflib.store', '__init__': <function NodePickler.__init__>, '_get_ids': <function NodePickler._get_ids>, 'register': <function NodePickler.register>, 'loads': <function NodePickler.loads>, 'dumps': <function NodePickler.dumps>, '__getstate__': <function NodePickler.__getstate__>, '__setstate__': <function NodePickler.__setstate__>, '__dict__': <attribute '__dict__' of 'NodePickler' objects>, '__weakref__': <attribute '__weakref__' of 'NodePickler' objects>, '__doc__': None, '__annotations__': {'_objects': 'Dict[str, Any]', '_ids': 'Dict[Any, str]'}})
__getstate__()[source]
Return type:

Mapping[str, Any]

__init__()[source]
__module__ = 'rdflib.store'
__setstate__(state)[source]
Parameters:

state (Mapping[str, Any]) –

Return type:

None

__weakref__

list of weak references to the object (if defined)

dumps(obj, protocol=None, bin=None)[source]
Parameters:
loads(s)[source]
Parameters:

s (bytes) –

Return type:

Node

register(object, id)[source]
Parameters:
  • object (Any) –

  • id (str) –

Return type:

None

class rdflib.store.Store(configuration=None, identifier=None)[source]

Bases: object

Parameters:
__annotations__ = {'context_aware': 'bool', 'formula_aware': 'bool', 'graph_aware': 'bool', 'transaction_aware': 'bool'}
__dict__ = mappingproxy({'__module__': 'rdflib.store', '__annotations__': {'context_aware': 'bool', 'formula_aware': 'bool', 'transaction_aware': 'bool', 'graph_aware': 'bool', '__node_pickler': 'Optional[NodePickler]'}, 'context_aware': False, 'formula_aware': False, 'transaction_aware': False, 'graph_aware': False, '__init__': <function Store.__init__>, 'node_pickler': <property object>, 'create': <function Store.create>, 'open': <function Store.open>, 'close': <function Store.close>, 'destroy': <function Store.destroy>, 'gc': <function Store.gc>, 'add': <function Store.add>, 'addN': <function Store.addN>, 'remove': <function Store.remove>, 'triples_choices': <function Store.triples_choices>, 'triples': <function Store.triples>, '__len__': <function Store.__len__>, 'contexts': <function Store.contexts>, 'query': <function Store.query>, 'update': <function Store.update>, 'bind': <function Store.bind>, 'prefix': <function Store.prefix>, 'namespace': <function Store.namespace>, 'namespaces': <function Store.namespaces>, 'commit': <function Store.commit>, 'rollback': <function Store.rollback>, 'add_graph': <function Store.add_graph>, 'remove_graph': <function Store.remove_graph>, '__dict__': <attribute '__dict__' of 'Store' objects>, '__weakref__': <attribute '__weakref__' of 'Store' objects>, '__doc__': None})
__init__(configuration=None, identifier=None)[source]

identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.

Parameters:
__len__(context=None)[source]

Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.

Parameters:

context (Optional[Graph]) – a graph instance to query or None

Return type:

int

__module__ = 'rdflib.store'
__weakref__

list of weak references to the object (if defined)

add(triple, context, quoted=False)[source]

Adds the given statement to a specific context or to the model. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical It should be an error to not specify a context and have the quoted argument be True. It should also be an error for the quoted argument to be True when the store is not formula-aware.

Parameters:
Return type:

None

addN(quads)[source]

Adds each item in the list of statements to a specific context. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical. Note that the default implementation is a redirect to add

Parameters:

quads (Iterable[Tuple[Node, Node, Node, Graph]]) –

Return type:

None

add_graph(graph)[source]

Add a graph to the store, no effect if the graph already exists. :type graph: Graph :param graph: a Graph instance

Return type:

None

bind(prefix, namespace, override=True)[source]
Parameters:
  • override (bool) – rebind, even if the given namespace is already bound to another prefix.

  • prefix (str) –

  • namespace (URIRef) –

Return type:

None

close(commit_pending_transaction=False)[source]

This closes the database connection. The commit_pending_transaction parameter specifies whether to commit all pending transactions before closing (if the store is transactional).

Parameters:

commit_pending_transaction (bool) –

Return type:

None

commit()[source]
Return type:

None

context_aware: bool = False
contexts(triple=None)[source]

Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.

if store is graph_aware, may also return empty contexts

Return type:

Generator[Graph, None, None]

Returns:

a generator over Nodes

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

create(configuration)[source]
Parameters:

configuration (str) –

Return type:

None

destroy(configuration)[source]

This destroys the instance of the store identified by the configuration string.

Parameters:

configuration (str) –

Return type:

None

formula_aware: bool = False
gc()[source]

Allows the store to perform any needed garbage collection

Return type:

None

graph_aware: bool = False
namespace(prefix)[source]
Parameters:

prefix (str) –

Return type:

Optional[URIRef]

namespaces()[source]
Return type:

Iterator[Tuple[str, URIRef]]

property node_pickler: NodePickler
open(configuration, create=False)[source]

Opens the store specified by the configuration string. If create is True a store will be created if it does not already exist. If create is False and a store does not already exist an exception is raised. An exception is also raised if a store exists, but there is insufficient permissions to open the store. This should return one of: VALID_STORE, CORRUPTED_STORE, or NO_STORE

Parameters:
  • configuration (str) –

  • create (bool) –

Return type:

Optional[int]

prefix(namespace)[source]
Parameters:

namespace (URIRef) –

Return type:

Optional[str]

query(query, initNs, initBindings, queryGraph, **kwargs)[source]

If stores provide their own SPARQL implementation, override this.

queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)

Parameters:
Return type:

Result

remove(triple, context=None)[source]

Remove the set of triples matching the pattern from the store

Parameters:
Return type:

None

remove_graph(graph)[source]

Remove a graph from the store, this should also remove all triples in the graph

Parameters:
  • graphid – a Graph instance

  • graph (Graph) –

Return type:

None

rollback()[source]
Return type:

None

transaction_aware: bool = False
triples(triple_pattern, context=None)[source]

A generator over all the triples matching the pattern. Pattern can include any objects for used for comparing against nodes in the store, for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph, QuotedGraph, Date? DateRange?

Parameters:
  • context (Optional[Graph]) – A conjunctive query can be indicated by either providing a value of None, or a specific context can be queries by passing a Graph instance (if store is context aware).

  • triple_pattern (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –

Return type:

Iterator[Tuple[Tuple[Node, Node, Node], Iterator[Optional[Graph]]]]

triples_choices(triple, context=None)[source]

A variant of triples that can take a list of terms instead of a single term in any slot. Stores can implement this to optimize the response time from the default ‘fallback’ implementation, which will iterate over each term in the list and dispatch to triples

Parameters:
Return type:

Generator[Tuple[Tuple[Node, Node, Node], Iterator[Optional[Graph]]], None, None]

update(update, initNs, initBindings, queryGraph, **kwargs)[source]

If stores provide their own (SPARQL) Update implementation, override this.

queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)

Parameters:
Return type:

None

class rdflib.store.StoreCreatedEvent(**kw)[source]

Bases: Event

This event is fired when the Store is created, it has the following attribute:

  • configuration: string used to create the store

__module__ = 'rdflib.store'
class rdflib.store.TripleAddedEvent(**kw)[source]

Bases: Event

This event is fired when a triple is added, it has the following attributes:

  • the triple added to the graph

  • the context of the triple, if any

  • the graph to which the triple was added

__module__ = 'rdflib.store'
class rdflib.store.TripleRemovedEvent(**kw)[source]

Bases: Event

This event is fired when a triple is removed, it has the following attributes:

  • the triple removed from the graph

  • the context of the triple, if any

  • the graph from which the triple was removed

__module__ = 'rdflib.store'

rdflib.term module

This module defines the different types of terms. Terms are the kinds of objects that can appear in a quoted/asserted triple. This includes those that are core to RDF:

Those that extend the RDF model into N3:

And those that are primarily for matching against ‘Nodes’ in the underlying Graph:

  • REGEX Expressions

  • Date Ranges

  • Numerical Ranges

class rdflib.term.BNode(value: str | None = None, _sn_gen: ~typing.Callable[[], str] = <function _serial_number_generator.<locals>._generator>, _prefix: str = 'N')[source]

Bases: IdentifiedNode

RDF 1.1’s Blank Nodes Section: https://www.w3.org/TR/rdf11-concepts/#section-blank-nodes

Blank Nodes are local identifiers for unnamed nodes in RDF graphs that are used in some concrete RDF syntaxes or RDF store implementations. They are always locally scoped to the file or RDF store, and are not persistent or portable identifiers for blank nodes. The identifiers for Blank Nodes are not part of the RDF abstract syntax, but are entirely dependent on particular concrete syntax or implementation (such as Turtle, JSON-LD).

RDFLib’s BNode class makes unique IDs for all the Blank Nodes in a Graph but you should never expect, or reply on, BNodes’ IDs to match across graphs, or even for multiple copies of the same graph, if they are regenerated from some non-RDFLib source, such as loading from RDF data.

__module__ = 'rdflib.term'
static __new__(cls, value=None, _sn_gen=<function _serial_number_generator.<locals>._generator>, _prefix='N')[source]

# only store implementations should pass in a value

Parameters:
Return type:

BNode

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[BNode], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

skolemize(authority=None, basepath=None)[source]

Create a URIRef “skolem” representation of the BNode, in accordance with http://www.w3.org/TR/rdf11-concepts/#section-skolemization

New in version 4.0.

Parameters:
Return type:

URIRef

class rdflib.term.IdentifiedNode(value: str)[source]

Bases: Identifier

An abstract class, primarily defined to identify Nodes that are not Literals.

The name “Identified Node” is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary

__dict__ = mappingproxy({'__module__': 'rdflib.term', '__doc__': '\n    An abstract class, primarily defined to identify Nodes that are not Literals.\n\n    The name "Identified Node" is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary\n    ', '__getnewargs__': <function IdentifiedNode.__getnewargs__>, 'toPython': <function IdentifiedNode.toPython>, '__dict__': <attribute '__dict__' of 'IdentifiedNode' objects>, '__weakref__': <attribute '__weakref__' of 'IdentifiedNode' objects>, '__annotations__': {}})
__getnewargs__()[source]
Return type:

Tuple[str]

__module__ = 'rdflib.term'
__weakref__

list of weak references to the object (if defined)

toPython()[source]
Return type:

str

class rdflib.term.Identifier(value: str)[source]

Bases: Node, str

See http://www.w3.org/2002/07/rdf-identifer-terminology/ regarding choice of terminology.

__eq__(other)[source]

Equality for Nodes.

>>> BNode("foo")==None
False
>>> BNode("foo")==URIRef("foo")
False
>>> URIRef("foo")==BNode("foo")
False
>>> BNode("foo")!=URIRef("foo")
True
>>> URIRef("foo")!=BNode("foo")
True
>>> Variable('a')!=URIRef('a')
True
>>> Variable('a')!=Variable('a')
False
Parameters:

other (Any) –

Return type:

bool

__ge__(other)[source]

Return self>=value.

Parameters:

other (Any) –

Return type:

bool

__gt__(other)[source]

This implements ordering for Nodes,

This tries to implement this: http://www.w3.org/TR/sparql11-query/#modOrderBy

Variables are not included in the SPARQL list, but they are greater than BNodes and smaller than everything else

Parameters:

other (Any) –

Return type:

bool

__hash__()

Return hash(self).

__le__(other)[source]

Return self<=value.

Parameters:

other (Any) –

Return type:

bool

__lt__(other)[source]

Return self<value.

Parameters:

other (Any) –

Return type:

bool

__module__ = 'rdflib.term'
__ne__(other)[source]

Return self!=value.

Parameters:

other (Any) –

Return type:

bool

static __new__(cls, value)[source]
Parameters:

value (str) –

Return type:

Identifier

__slots__ = ()
eq(other)[source]

A “semantic”/interpreted equality function, by default, same as __eq__

Parameters:

other (Any) –

Return type:

bool

neq(other)[source]

A “semantic”/interpreted not equal function, by default, same as __ne__

Parameters:

other (Any) –

Return type:

bool

startswith(prefix, start=Ellipsis, end=Ellipsis)[source]

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

Parameters:

prefix (str) –

Return type:

bool

class rdflib.term.Literal(lexical_or_value: Any, lang: str | None = None, datatype: str | None = None, normalize: bool | None = None)[source]

Bases: Identifier

RDF 1.1’s Literals Section: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal

Literals are used for values such as strings, numbers, and dates.

A literal in an RDF graph consists of two or three elements:

  • a lexical form, being a Unicode string, which SHOULD be in Normal Form C

  • a datatype IRI, being an IRI identifying a datatype that determines how the lexical form maps to a literal value, and

  • if and only if the datatype IRI is http://www.w3.org/1999/02/22-rdf-syntax-ns#langString, a non-empty language tag. The language tag MUST be well-formed according to section 2.2.9 of Tags for identifying languages.

A literal is a language-tagged string if the third element is present. Lexical representations of language tags MAY be converted to lower case. The value space of language tags is always in lower case.

For valid XSD datatypes, the lexical form is optionally normalized at construction time. Default behaviour is set by rdflib.NORMALIZE_LITERALS and can be overridden by the normalize parameter to __new__

Equality and hashing of Literals are done based on the lexical form, i.e.:

>>> from rdflib.namespace import XSD
>>> Literal('01') != Literal('1')  # clear - strings differ
True

but with data-type they get normalized:

>>> Literal('01', datatype=XSD.integer) != Literal('1', datatype=XSD.integer)
False

unless disabled:

>>> Literal('01', datatype=XSD.integer, normalize=False) != Literal('1', datatype=XSD.integer)
True

Value based comparison is possible:

>>> Literal('01', datatype=XSD.integer).eq(Literal('1', datatype=XSD.float))
True

The eq method also provides limited support for basic python types:

>>> Literal(1).eq(1) # fine - int compatible with xsd:integer
True
>>> Literal('a').eq('b') # fine - str compatible with plain-lit
False
>>> Literal('a', datatype=XSD.string).eq('a') # fine - str compatible with xsd:string
True
>>> Literal('a').eq(1) # not fine, int incompatible with plain-lit
NotImplemented

Greater-than/less-than ordering comparisons are also done in value space, when compatible datatypes are used. Incompatible datatypes are ordered by DT, or by lang-tag. For other nodes the ordering is None < BNode < URIRef < Literal

Any comparison with non-rdflib Node are “NotImplemented” In PY3 this is an error.

>>> from rdflib import Literal, XSD
>>> lit2006 = Literal('2006-01-01',datatype=XSD.date)
>>> lit2006.toPython()
datetime.date(2006, 1, 1)
>>> lit2006 < Literal('2007-01-01',datatype=XSD.date)
True
>>> Literal(datetime.utcnow()).datatype
rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime')
>>> Literal(1) > Literal(2) # by value
False
>>> Literal(1) > Literal(2.0) # by value
False
>>> Literal('1') > Literal(1) # by DT
True
>>> Literal('1') < Literal('1') # by lexical form
False
>>> Literal('a', lang='en') > Literal('a', lang='fr') # by lang-tag
False
>>> Literal(1) > URIRef('foo') # by node-type
True

The > < operators will eat this NotImplemented and throw a TypeError (py3k):

>>> Literal(1).__gt__(2.0)
NotImplemented
__abs__()[source]
Return type:

Literal

>>> abs(Literal(-1))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> abs( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> abs(Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__add__(val)[source]
>>> from rdflib.namespace import XSD
>>> Literal(1) + 1
rdflib.term.Literal('2', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal("1") + "1"
rdflib.term.Literal('11')

# Handling dateTime/date/time based operations in Literals >>> a = Literal(‘2006-01-01T20:50:00’, datatype=XSD.dateTime) >>> b = Literal(‘P31D’, datatype=XSD.duration) >>> (a + b) rdflib.term.Literal(‘2006-02-01T20:50:00’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#dateTime’)) >>> from rdflib.namespace import XSD >>> a = Literal(‘2006-07-01T20:52:00’, datatype=XSD.dateTime) >>> b = Literal(‘P122DT15H58M’, datatype=XSD.duration) >>> (a + b) rdflib.term.Literal(‘2006-11-01T12:50:00’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#dateTime’))

Parameters:

val (Any) –

Return type:

Literal

__annotations__ = {'_datatype': typing.Optional[rdflib.term.URIRef], '_ill_typed': typing.Optional[bool], '_language': typing.Optional[str], '_value': typing.Any}
__bool__()[source]

Is the Literal “True” This is used for if statements, bool(literal), etc.

Return type:

bool

__eq__(other)[source]

Literals are only equal to other literals.

“Two literals are equal if and only if all of the following hold: * The strings of the two lexical forms compare equal, character by character. * Either both or neither have language tags. * The language tags, if any, compare equal. * Either both or neither have datatype URIs. * The two datatype URIs, if any, compare equal, character by character.” – 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)

>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo"))
True
>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo2"))
False
>>> Literal("1", datatype=URIRef("foo")) == Literal("2", datatype=URIRef("foo"))
False
>>> Literal("1", datatype=URIRef("foo")) == "asdf"
False
>>> from rdflib import XSD
>>> Literal('2007-01-01', datatype=XSD.date) == Literal('2007-01-01', datatype=XSD.date)
True
>>> Literal('2007-01-01', datatype=XSD.date) == date(2007, 1, 1)
False
>>> Literal("one", lang="en") == Literal("one", lang="en")
True
>>> Literal("hast", lang='en') == Literal("hast", lang='de')
False
>>> Literal("1", datatype=XSD.integer) == Literal(1)
True
>>> Literal("1", datatype=XSD.integer) == Literal("01", datatype=XSD.integer)
True
Parameters:

other (Any) –

Return type:

bool

__ge__(other)[source]

Return self>=value.

Parameters:

other (Any) –

Return type:

bool

__getstate__()[source]
Return type:

Tuple[None, Dict[str, Optional[str]]]

__gt__(other)[source]

This implements ordering for Literals, the other comparison methods delegate here

This tries to implement this: http://www.w3.org/TR/sparql11-query/#modOrderBy

In short, Literals with compatible data-types are ordered in value space, i.e. >>> from rdflib import XSD

>>> Literal(1) > Literal(2) # int/int
False
>>> Literal(2.0) > Literal(1) # double/int
True
>>> from decimal import Decimal
>>> Literal(Decimal("3.3")) > Literal(2.0) # decimal/double
True
>>> Literal(Decimal("3.3")) < Literal(4.0) # decimal/double
True
>>> Literal('b') > Literal('a') # plain lit/plain lit
True
>>> Literal('b') > Literal('a', datatype=XSD.string) # plain lit/xsd:str
True

Incompatible datatype mismatches ordered by DT

>>> Literal(1) > Literal("2") # int>string
False

Langtagged literals by lang tag >>> Literal(“a”, lang=”en”) > Literal(“a”, lang=”fr”) False

Parameters:

other (Any) –

Return type:

bool

__hash__()[source]
>>> from rdflib.namespace import XSD
>>> a = {Literal('1', datatype=XSD.integer):'one'}
:rtype: :py:class:`int`
>>> Literal('1', datatype=XSD.double) in a
False

“Called for the key object for dictionary operations, and by the built-in function hash(). Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects.” – 3.4.1 Basic customization (Python)

“Two literals are equal if and only if all of the following hold: * The strings of the two lexical forms compare equal, character by character. * Either both or neither have language tags. * The language tags, if any, compare equal. * Either both or neither have datatype URIs. * The two datatype URIs, if any, compare equal, character by character.” – 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)

__invert__()[source]
Return type:

Literal

>>> ~(Literal(-1))
rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> ~( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))

Not working:

>>> ~(Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__le__(other)[source]
>>> from rdflib.namespace import XSD
>>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
...     ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
True
Parameters:

other (Any) –

Return type:

bool

__lt__(other)[source]

Return self<value.

Parameters:

other (Any) –

Return type:

bool

__module__ = 'rdflib.term'
__neg__()[source]
>>> (- Literal(1))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal(10.5))
rdflib.term.Literal('-10.5', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double'))
>>> from rdflib.namespace import XSD
:rtype: :py:class:`~rdflib.term.Literal`
>>> (- Literal("1", datatype=XSD.integer))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
>>>
static __new__(cls, lexical_or_value, lang=None, datatype=None, normalize=None)[source]
Parameters:
Return type:

Literal

__pos__()[source]
>>> (+ Literal(1))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal(-1))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
:rtype: :py:class:`~rdflib.term.Literal`
>>> (+ Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Literal], Tuple[str, Optional[str], Optional[str]]]

__repr__()[source]

Return repr(self).

Return type:

str

__setstate__(arg)[source]
Parameters:

arg (Tuple[Any, Dict[str, Any]]) –

Return type:

None

__slots__ = ('_language', '_datatype', '_value', '_ill_typed')
__sub__(val)[source]
>>> from rdflib.namespace import XSD
>>> Literal(2) - 1
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal(1.1) - 1.0
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double'))
>>> Literal(1.1) - 1
rdflib.term.Literal('0.1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#decimal'))
>>> Literal(1.1, datatype=XSD.float) - Literal(1.0, datatype=XSD.float)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#float'))
>>> Literal("1.1") - 1.0 
Traceback (most recent call last):
...
TypeError: Not a number; rdflib.term.Literal('1.1')
>>> Literal(1.1, datatype=XSD.integer) - Literal(1.0, datatype=XSD.integer)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))

# Handling dateTime/date/time based operations in Literals >>> a = Literal(‘2006-01-01T20:50:00’, datatype=XSD.dateTime) >>> b = Literal(‘2006-02-01T20:50:00’, datatype=XSD.dateTime) >>> (b - a) rdflib.term.Literal(‘P31D’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’)) >>> from rdflib.namespace import XSD >>> a = Literal(‘2006-07-01T20:52:00’, datatype=XSD.dateTime) >>> b = Literal(‘2006-11-01T12:50:00’, datatype=XSD.dateTime) >>> (a - b) rdflib.term.Literal(‘-P122DT15H58M’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’)) >>> (b - a) rdflib.term.Literal(‘P122DT15H58M’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’))

Parameters:

val (Any) –

Return type:

Literal

property datatype: URIRef | None
eq(other)[source]

Compare the value of this literal with something else

Either, with the value of another literal comparisons are then done in literal “value space”, and according to the rules of XSD subtype-substitution/type-promotion

OR, with a python object:

basestring objects can be compared with plain-literals, or those with datatype xsd:string

bool objects with xsd:boolean

a int, long or float with numeric xsd types

isodate date,time,datetime objects with xsd:date,xsd:time or xsd:datetime

Any other operations returns NotImplemented

Parameters:

other (Any) –

Return type:

bool

property ill_typed: bool | None

For recognized datatype IRIs, this value will be True if the literal is ill formed, otherwise it will be False. Literal.value (i.e. the literal value) should always be defined if this property is False, but should not be considered reliable if this property is True.

If the literal’s datatype is None or not in the set of recognized datatype IRIs this value will be None.

property language: str | None
n3(namespace_manager=None)[source]

Returns a representation in the N3 format.

Examples:

>>> Literal("foo").n3()
'"foo"'

Strings with newlines or triple-quotes:

>>> Literal("foo\nbar").n3()
'"""foo\nbar"""'

>>> Literal("''\'").n3()
'"\'\'\'"'

>>> Literal('"""').n3()
'"\\"\\"\\""'

Language:

>>> Literal("hello", lang="en").n3()
'"hello"@en'

Datatypes:

>>> Literal(1).n3()
'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

>>> Literal(1.0).n3()
'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'

>>> Literal(True).n3()
'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'

Datatype and language isn’t allowed (datatype takes precedence):

>>> Literal(1, lang="en").n3()
'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

Custom datatype:

>>> footype = URIRef("http://example.org/ns#foo")
>>> Literal("1", datatype=footype).n3()
'"1"^^<http://example.org/ns#foo>'

Passing a namespace-manager will use it to abbreviate datatype URIs:

>>> from rdflib import Graph
>>> Literal(1).n3(Graph().namespace_manager)
'"1"^^xsd:integer'
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

neq(other)[source]

A “semantic”/interpreted not equal function, by default, same as __ne__

Parameters:

other (Any) –

Return type:

bool

normalize()[source]

Returns a new literal with a normalised lexical representation of this literal >>> from rdflib import XSD >>> Literal(“01”, datatype=XSD.integer, normalize=False).normalize() rdflib.term.Literal(‘1’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

Illegal lexical forms for the datatype given are simply passed on >>> Literal(“a”, datatype=XSD.integer, normalize=False) rdflib.term.Literal(‘a’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

Return type:

Literal

toPython()[source]

Returns an appropriate python datatype derived from this RDF Literal

Return type:

Any

property value: Any
class rdflib.term.Node[source]

Bases: object

A Node in the Graph.

__module__ = 'rdflib.term'
__slots__ = ()
class rdflib.term.URIRef(value: str, base: str | None = None)[source]

Bases: IdentifiedNode

RDF 1.1’s IRI Section https://www.w3.org/TR/rdf11-concepts/#section-IRIs

Note

Documentation on RDF outside of RDFLib uses the term IRI or URI whereas this class is called URIRef. This is because it was made when the first version of the RDF specification was current, and it used the term URIRef, see RDF 1.0 URIRef

An IRI (Internationalized Resource Identifier) within an RDF graph is a Unicode string that conforms to the syntax defined in RFC 3987.

IRIs in the RDF abstract syntax MUST be absolute, and MAY contain a fragment identifier.

IRIs are a generalization of URIs [RFC3986] that permits a wider range of Unicode characters.

__add__(other)[source]

Return self+value.

Return type:

URIRef

__annotations__ = {'__invert__': typing.Callable[[ForwardRef('URIRef')], ForwardRef('InvPath')], '__neg__': typing.Callable[[ForwardRef('URIRef')], ForwardRef('NegatedPath')], '__or__': typing.Callable[[ForwardRef('URIRef'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('AlternativePath')], '__truediv__': typing.Callable[[ForwardRef('URIRef'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('SequencePath')]}
__invert__()

inverse path

Parameters:

p (Union[URIRef, Path]) –

Return type:

InvPath

__mod__(other)[source]

Return self%value.

Return type:

URIRef

__module__ = 'rdflib.term'
__mul__(mul)

cardinality path

Parameters:
Return type:

MulPath

__neg__()

negated path

Parameters:

p (Union[URIRef, AlternativePath, InvPath]) –

Return type:

NegatedPath

static __new__(cls, value, base=None)[source]
Parameters:
Return type:

URIRef

__or__(other)

alternative path

Parameters:
__radd__(other)[source]
Return type:

URIRef

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[URIRef], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
__truediv__(other)

sequence path

Parameters:
de_skolemize()[source]

Create a Blank Node from a skolem URI, in accordance with http://www.w3.org/TR/rdf11-concepts/#section-skolemization. This function accepts only rdflib type skolemization, to provide a round-tripping within the system. :rtype: BNode

New in version 4.0.

defrag()[source]
Return type:

URIRef

property fragment: str

Return the URL Fragment

>>> URIRef("http://example.com/some/path/#some-fragment").fragment
'some-fragment'
>>> URIRef("http://example.com/some/path/").fragment
''
n3(namespace_manager=None)[source]

This will do a limited check for valid URIs, essentially just making sure that the string includes no illegal characters (<, >, ", {, }, |, \, `, ^)

Parameters:

namespace_manager (Optional[NamespaceManager]) – if not None, will be used to make up a prefixed name

Return type:

str

class rdflib.term.Variable(value: str)[source]

Bases: Identifier

A Variable - this is used for querying, or in Formula aware graphs, where Variables can be stored

__module__ = 'rdflib.term'
static __new__(cls, value)[source]
Parameters:

value (str) –

Return type:

Variable

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Variable], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

toPython()[source]
Return type:

str

rdflib.term.bind(datatype, pythontype, constructor=None, lexicalizer=None, datatype_specific=False)[source]

register a new datatype<->pythontype binding

Parameters:
  • constructor (Optional[Callable[[str], Any]]) – an optional function for converting lexical forms into a Python instances, if not given the pythontype is used directly

  • lexicalizer (Optional[Callable[[Any], Union[str, bytes]]]) – an optional function for converting python objects to lexical form, if not given object.__str__ is used

  • datatype_specific (bool) – makes the lexicalizer function be accessible from the pair (pythontype, datatype) if set to True or from the pythontype otherwise. False by default

  • datatype (str) –

  • pythontype (Type[Any]) –

Return type:

None

rdflib.util module

rdflib.util.date_time(t=None, local_time_zone=False)[source]

http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z

>>> date_time(1126482850)
'2005-09-11T23:54:10Z'

@@ this will change depending on where it is run #>>> date_time(1126482850, local_time_zone=True) #’2005-09-11T19:54:10-04:00’

>>> date_time(1)
'1970-01-01T00:00:01Z'
>>> date_time(0)
'1970-01-01T00:00:00Z'
rdflib.util.find_roots(graph, prop, roots=None)[source]

Find the roots in some sort of transitive hierarchy.

find_roots(graph, rdflib.RDFS.subClassOf) will return a set of all roots of the sub-class hierarchy

Assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader

Parameters:
Return type:

Set[Node]

rdflib.util.first(seq)[source]

return the first element in a python sequence for graphs, use graph.value instead

Parameters:

seq (Iterable[TypeVar(_AnyT)]) –

Return type:

Optional[TypeVar(_AnyT)]

rdflib.util.from_n3(s, default=None, backend=None, nsm=None)[source]

Creates the Identifier corresponding to the given n3 string.

>>> from rdflib.term import URIRef, Literal
>>> from rdflib.namespace import NamespaceManager
>>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo')
True
>>> from_n3('"foo"@de') == Literal('foo', lang='de')
True
>>> from_n3('"""multi\nline\nstring"""@en') == Literal(
...     'multi\nline\nstring', lang='en')
True
>>> from_n3('42') == Literal(42)
True
>>> from_n3(Literal(42).n3()) == Literal(42)
True
>>> from_n3('"42"^^xsd:integer') == Literal(42)
True
>>> from rdflib import RDFS
>>> from_n3('rdfs:label') == RDFS['label']
True
>>> nsm = NamespaceManager(rdflib.graph.Graph())
>>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/')
>>> berlin = URIRef('http://dbpedia.org/resource/Berlin')
>>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin
True
Parameters:
Return type:

Union[Node, str, None]

rdflib.util.get_tree(graph, root, prop, mapper=<function <lambda>>, sortkey=None, done=None, dir='down')[source]

Return a nested list/tuple structure representing the tree built by the transitive property given, starting from the root given

i.e.

get_tree(graph,

rdflib.URIRef(”http://xmlns.com/foaf/0.1/Person”), rdflib.RDFS.subClassOf)

will return the structure for the subClassTree below person.

dir=’down’ assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader Any other dir traverses in the other direction

Parameters:
Return type:

Optional[Tuple[Node, List[Any]]]

rdflib.util.guess_format(fpath, fmap=None)[source]

Guess RDF serialization based on file suffix. Uses SUFFIX_FORMAT_MAP unless fmap is provided. Examples:

>>> guess_format('path/to/file.rdf')
'xml'
>>> guess_format('path/to/file.owl')
'xml'
>>> guess_format('path/to/file.ttl')
'turtle'
>>> guess_format('path/to/file.json')
'json-ld'
>>> guess_format('path/to/file.xhtml')
'rdfa'
>>> guess_format('path/to/file.svg')
'rdfa'
>>> guess_format('path/to/file.xhtml', {'xhtml': 'grddl'})
'grddl'

This also works with just the suffixes, with or without leading dot, and regardless of letter case:

>>> guess_format('.rdf')
'xml'
>>> guess_format('rdf')
'xml'
>>> guess_format('RDF')
'xml'
Parameters:
Return type:

Optional[str]

rdflib.util.list2set(seq)[source]

Return a new list without duplicates. Preserves the order, unlike set(seq)

Parameters:

seq (Iterable[TypeVar(_HashableT, bound= Hashable)]) –

Return type:

List[TypeVar(_HashableT, bound= Hashable)]

rdflib.util.more_than(sequence, number)[source]

Returns 1 if sequence has more items than number and 0 if not.

Parameters:
Return type:

int

rdflib.util.parse_date_time(val)[source]

always returns seconds in UTC

# tests are written like this to make any errors easier to understand >>> parse_date_time(‘2005-09-11T23:54:10Z’) - 1126482850.0 0.0

>>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0
0.0
>>> parse_date_time('1970-01-01T00:00:01Z') - 1.0
0.0
>>> parse_date_time('1970-01-01T00:00:00Z') - 0.0
0.0
>>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0
0.0
Parameters:

val (str) –

Return type:

int

rdflib.util.to_term(s, default=None)[source]

Creates and returns an Identifier of type corresponding to the pattern of the given positional argument string s:

‘’ returns the default keyword argument value or None

‘<s>’ returns URIRef(s) (i.e. without angle brackets)

‘“s”’ returns Literal(s) (i.e. without doublequotes)

‘_s’ returns BNode(s) (i.e. without leading underscore)

Parameters:
Return type:

Optional[Identifier]

rdflib.util.uniq(sequence, strip=0)[source]

removes duplicate strings from the sequence.

Parameters:
Return type:

Set[str]

rdflib.void module

rdflib.void.generateVoID(g, dataset=None, res=None, distinctForPartitions=True)[source]

Returns a new graph with a VoID description of the passed dataset

For more info on Vocabulary of Interlinked Datasets (VoID), see: http://vocab.deri.ie/void

This only makes two passes through the triples (once to detect the types of things)

The tradeoff is that lots of temporary structures are built up in memory meaning lots of memory may be consumed :) I imagine at least a few copies of your original graph.

the distinctForPartitions parameter controls whether distinctSubjects/objects are tracked for each class/propertyPartition this requires more memory again

Module contents

A pure Python package providing the core RDF constructs.

The packages is intended to provide the core RDF types and interfaces for working with RDF. The package defines a plugin interface for parsers, stores, and serializers that other packages can use to implement parsers, stores, and serializers that will plug into the rdflib package.

The primary interface rdflib exposes to work with RDF is rdflib.graph.Graph.

A tiny example:

>>> from rdflib import Graph, URIRef, Literal
>>> g = Graph()
>>> result = g.parse("http://www.w3.org/2000/10/swap/test/meet/blue.rdf")
>>> print("graph has %s statements." % len(g))
graph has 4 statements.
>>>
>>> for s, p, o in g:
...     if (s, p, o) not in g:
...         raise Exception("It better be!")
>>> s = g.serialize(format='nt')
>>>
>>> sorted(g) == [
...  (URIRef("http://meetings.example.com/cal#m1"),
...   URIRef("http://www.example.org/meeting_organization#homePage"),
...   URIRef("http://meetings.example.com/m1/hp")),
...  (URIRef("http://www.example.org/people#fred"),
...   URIRef("http://www.example.org/meeting_organization#attending"),
...   URIRef("http://meetings.example.com/cal#m1")),
...  (URIRef("http://www.example.org/people#fred"),
...   URIRef("http://www.example.org/personal_details#GivenName"),
...   Literal("Fred")),
...  (URIRef("http://www.example.org/people#fred"),
...   URIRef("http://www.example.org/personal_details#hasEmail"),
...   URIRef("mailto:fred@example.com"))
... ]
True
class rdflib.BNode(value: str | None = None, _sn_gen: ~typing.Callable[[], str] = <function _serial_number_generator.<locals>._generator>, _prefix: str = 'N')[source]

Bases: IdentifiedNode

RDF 1.1’s Blank Nodes Section: https://www.w3.org/TR/rdf11-concepts/#section-blank-nodes

Blank Nodes are local identifiers for unnamed nodes in RDF graphs that are used in some concrete RDF syntaxes or RDF store implementations. They are always locally scoped to the file or RDF store, and are not persistent or portable identifiers for blank nodes. The identifiers for Blank Nodes are not part of the RDF abstract syntax, but are entirely dependent on particular concrete syntax or implementation (such as Turtle, JSON-LD).

RDFLib’s BNode class makes unique IDs for all the Blank Nodes in a Graph but you should never expect, or reply on, BNodes’ IDs to match across graphs, or even for multiple copies of the same graph, if they are regenerated from some non-RDFLib source, such as loading from RDF data.

__annotations__ = {}
__module__ = 'rdflib.term'
static __new__(cls, value=None, _sn_gen=<function _serial_number_generator.<locals>._generator>, _prefix='N')[source]

# only store implementations should pass in a value

Parameters:
Return type:

BNode

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[BNode], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

skolemize(authority=None, basepath=None)[source]

Create a URIRef “skolem” representation of the BNode, in accordance with http://www.w3.org/TR/rdf11-concepts/#section-skolemization

New in version 4.0.

Parameters:
Return type:

URIRef

class rdflib.ConjunctiveGraph(store='default', identifier=None, default_graph_base=None)[source]

Bases: Graph

A ConjunctiveGraph is an (unnamed) aggregation of all the named graphs in a store.

It has a default graph, whose name is associated with the graph throughout its life. __init__() can take an identifier to use as the name of this default graph or it will assign a BNode.

All methods that add triples work against this default graph.

All queries are carried out against the union of all graphs.

Parameters:
__annotations__ = {'__identifier': '_ContextIdentifierType', '__store': 'Store', 'default_context': '_ContextType'}
__contains__(triple_or_quad)[source]

Support for ‘triple/quad in graph’ syntax

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]], Tuple[Optional[Node], Union[Path, Node, None], Optional[Node], Optional[Graph]]]) –

Return type:

bool

__init__(store='default', identifier=None, default_graph_base=None)[source]
Parameters:
__len__()[source]

Number of triples in the entire conjunctive graph

Return type:

int

__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]

__str__()[source]

Return str(self).

Return type:

str

add(triple_or_quad)[source]

Add a triple or quad to the store.

if a triple is given it is added to the default context

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

addN(quads)[source]

Add a sequence of triples with context

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

context_id(uri, context_id=None)[source]

URI#context

Parameters:
Return type:

URIRef

contexts(triple=None)[source]

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

default_context: Graph
get_context(identifier, quoted=False, base=None)[source]

Return a context graph for the given identifier

identifier must be a URIRef or BNode.

Parameters:
Return type:

Graph

get_graph(identifier)[source]

Returns the graph identified by given identifier

Parameters:

identifier (IdentifiedNode) –

Return type:

Optional[Graph]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse source adding the resulting triples to its own context (sub graph of this graph).

See rdflib.graph.Graph.parse() for documentation on arguments.

If the source is in a format that does not support named graphs it’s triples will be added to the default graph (i.e. Dataset.default_context).

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root context.

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Changed in 7.0: The publicID argument is no longer used as the identifier (i.e. name) of the default graph as was the case before version 7.0. In the case of sources that do not support named graphs, the publicID parameter will also not be used as the name for the graph that the data is loaded into, and instead the triples from sources that do not support named graphs will be loaded into the default graph (i.e. ConjunctionGraph.default_context).

Parameters:
Return type:

Graph

quads(triple_or_quad=None)[source]

Iterate over all the quads in the entire conjunctive graph

Parameters:

triple_or_quad (Union[Tuple[Optional[Node], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], Optional[Node], Optional[Graph]], None]) –

Return type:

Generator[Tuple[Node, Node, Node, Optional[Graph]], None, None]

remove(triple_or_quad)[source]

Removes a triple or quads

if a triple is given it is removed from all contexts

a quad is removed from the given context only

Parameters:
Return type:

TypeVar(_ConjunctiveGraphT, bound= ConjunctiveGraph)

remove_context(context)[source]

Removes the given context from the graph

Parameters:

context (Graph) –

Return type:

None

triples(triple_or_quad, context=None)[source]

Iterate over all the triples in the entire conjunctive graph

For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.

Parameters:
Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

triples_choices(triple, context=None)[source]

Iterate over all the triples in the entire conjunctive graph

Parameters:
Return type:

Generator[Tuple[Node, Node, Node], None, None]

class rdflib.Dataset(store='default', default_union=False, default_graph_base=None)[source]

Bases: ConjunctiveGraph

RDF 1.1 Dataset. Small extension to the Conjunctive Graph: - the primary term is graphs in the datasets and not contexts with quads, so there is a separate method to set/retrieve a graph in a dataset and operate with graphs - graphs cannot be identified with blank nodes - added a method to directly add a single quad

Examples of usage:

>>> # Create a new Dataset
>>> ds = Dataset()
>>> # simple triples goes to default graph
>>> ds.add((URIRef("http://example.org/a"),
...    URIRef("http://www.example.org/b"),
...    Literal("foo")))  
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>>
>>> # Create a graph in the dataset, if the graph name has already been
>>> # used, the corresponding graph will be returned
>>> # (ie, the Dataset keeps track of the constituent graphs)
>>> g = ds.graph(URIRef("http://www.example.com/gr"))
>>>
>>> # add triples to the new graph as usual
>>> g.add(
...     (URIRef("http://example.org/x"),
...     URIRef("http://example.org/y"),
...     Literal("bar")) ) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> # alternatively: add a quad to the dataset -> goes to the graph
>>> ds.add(
...     (URIRef("http://example.org/x"),
...     URIRef("http://example.org/z"),
...     Literal("foo-bar"),g) ) 
<Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
>>>
>>> # querying triples return them all regardless of the graph
>>> for t in ds.triples((None,None,None)):  
...     print(t)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"))
>>>
>>> # querying quads() return quads; the fourth argument can be unrestricted
>>> # (None) or restricted to a graph
>>> for q in ds.quads((None, None, None, None)):  
...     print(q)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"),
 None)
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>>
>>> # unrestricted looping is equivalent to iterating over the entire Dataset
>>> for q in ds:  
...     print(q)  
(rdflib.term.URIRef("http://example.org/a"),
 rdflib.term.URIRef("http://www.example.org/b"),
 rdflib.term.Literal("foo"),
 None)
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>>
>>> # resticting iteration to a graph:
>>> for q in ds.quads((None, None, None, g)):  
...     print(q)  
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/y"),
 rdflib.term.Literal("bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
(rdflib.term.URIRef("http://example.org/x"),
 rdflib.term.URIRef("http://example.org/z"),
 rdflib.term.Literal("foo-bar"),
 rdflib.term.URIRef("http://www.example.com/gr"))
>>> # Note that in the call above -
>>> # ds.quads((None,None,None,"http://www.example.com/gr"))
>>> # would have been accepted, too
>>>
>>> # graph names in the dataset can be queried:
>>> for c in ds.graphs():  
...     print(c)  # doctest:
DEFAULT
http://www.example.com/gr
>>> # A graph can be created without specifying a name; a skolemized genid
>>> # is created on the fly
>>> h = ds.graph()
>>> for c in ds.graphs():  
...     print(c)  
DEFAULT
https://rdflib.github.io/.well-known/genid/rdflib/N...
http://www.example.com/gr
>>> # Note that the Dataset.graphs() call returns names of empty graphs,
>>> # too. This can be restricted:
>>> for c in ds.graphs(empty=False):  
...     print(c)  
DEFAULT
http://www.example.com/gr
>>>
>>> # a graph can also be removed from a dataset via ds.remove_graph(g)

New in version 4.0.

Parameters:
__annotations__ = {'__identifier': '_ContextIdentifierType', '__store': 'Store', 'default_context': '_ContextType'}
__getstate__()[source]
Return type:

Tuple[Store, IdentifiedNode, Graph, bool]

__init__(store='default', default_union=False, default_graph_base=None)[source]
Parameters:
__iter__()[source]

Iterates over all quads in the store

Return type:

Generator[Tuple[Node, Node, Node, Optional[IdentifiedNode]], None, None]

__module__ = 'rdflib.graph'
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Dataset], Tuple[Store, bool]]

__setstate__(state)[source]
Parameters:

state (Tuple[Store, IdentifiedNode, Graph, bool]) –

Return type:

None

__str__()[source]

Return str(self).

Return type:

str

add_graph(g)[source]

alias of graph for consistency

Parameters:

g (Union[IdentifiedNode, Graph, str, None]) –

Return type:

Graph

contexts(triple=None)[source]

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

default_context: Graph
graph(identifier=None, base=None)[source]
Parameters:
Return type:

Graph

graphs(triple=None)

Iterate over all contexts in the graph

If triple is specified, iterate over all contexts the triple is in.

Parameters:

triple (Optional[Tuple[Node, Node, Node]]) –

Return type:

Generator[Graph, None, None]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse an RDF source adding the resulting triples to the Graph.

See rdflib.graph.Graph.parse() for documentation on arguments.

The source is specified using one of source, location, file or data.

If the source is in a format that does not support named graphs it’s triples will be added to the default graph (i.e. Dataset.default_context).

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Changed in 7.0: The publicID argument is no longer used as the identifier (i.e. name) of the default graph as was the case before version 7.0. In the case of sources that do not support named graphs, the publicID parameter will also not be used as the name for the graph that the data is loaded into, and instead the triples from sources that do not support named graphs will be loaded into the default graph (i.e. ConjunctionGraph.default_context).

Parameters:
Return type:

Graph

quads(quad=None)[source]

Iterate over all the quads in the entire conjunctive graph

Parameters:

quad (Union[Tuple[Optional[Node], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], Optional[Node], Optional[Graph]], None]) –

Return type:

Generator[Tuple[Node, Node, Node, Optional[IdentifiedNode]], None, None]

remove_graph(g)[source]
Parameters:
Return type:

TypeVar(_DatasetT, bound= Dataset)

class rdflib.Graph(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]

Bases: Node

An RDF Graph

The constructor accepts one argument, the “store” that will be used to store the graph data (see the “store” package for stores currently shipped with rdflib).

Stores can be context-aware or unaware. Unaware stores take up (some) less space but cannot support features that require context, such as true merging/demerging of sub-graphs and provenance.

Even if used with a context-aware store, Graph will only expose the quads which belong to the default graph. To access the rest of the data, ConjunctiveGraph or Dataset classes can be used instead.

The Graph constructor can take an identifier which identifies the Graph by name. If none is given, the graph is assigned a BNode for its identifier.

For more on named graphs, see: http://www.w3.org/2004/03/trix/

Parameters:
__add__(other)[source]

Set-theoretic union BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__and__(other)

Set-theoretic intersection. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__annotations__ = {'__identifier': '_ContextIdentifierType', '__store': 'Store'}
__cmp__(other)[source]
Return type:

int

__contains__(triple)[source]

Support for ‘triple in graph’ syntax

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.graph', '__doc__': 'An RDF Graph\n\n    The constructor accepts one argument, the "store"\n    that will be used to store the graph data (see the "store"\n    package for stores currently shipped with rdflib).\n\n    Stores can be context-aware or unaware.  Unaware stores take up\n    (some) less space but cannot support features that require\n    context, such as true merging/demerging of sub-graphs and\n    provenance.\n\n    Even if used with a context-aware store, Graph will only expose the quads which\n    belong to the default graph. To access the rest of the data, `ConjunctiveGraph` or\n    `Dataset` classes can be used instead.\n\n    The Graph constructor can take an identifier which identifies the Graph\n    by name.  If none is given, the graph is assigned a BNode for its\n    identifier.\n\n    For more on named graphs, see: http://www.w3.org/2004/03/trix/\n    ', '__init__': <function Graph.__init__>, 'store': <property object>, 'identifier': <property object>, 'namespace_manager': <property object>, '__repr__': <function Graph.__repr__>, '__str__': <function Graph.__str__>, 'toPython': <function Graph.toPython>, 'destroy': <function Graph.destroy>, 'commit': <function Graph.commit>, 'rollback': <function Graph.rollback>, 'open': <function Graph.open>, 'close': <function Graph.close>, 'add': <function Graph.add>, 'addN': <function Graph.addN>, 'remove': <function Graph.remove>, 'triples': <function Graph.triples>, '__getitem__': <function Graph.__getitem__>, '__len__': <function Graph.__len__>, '__iter__': <function Graph.__iter__>, '__contains__': <function Graph.__contains__>, '__hash__': <function Graph.__hash__>, '__cmp__': <function Graph.__cmp__>, '__eq__': <function Graph.__eq__>, '__lt__': <function Graph.__lt__>, '__le__': <function Graph.__le__>, '__gt__': <function Graph.__gt__>, '__ge__': <function Graph.__ge__>, '__iadd__': <function Graph.__iadd__>, '__isub__': <function Graph.__isub__>, '__add__': <function Graph.__add__>, '__mul__': <function Graph.__mul__>, '__sub__': <function Graph.__sub__>, '__xor__': <function Graph.__xor__>, '__or__': <function Graph.__add__>, '__and__': <function Graph.__mul__>, 'set': <function Graph.set>, 'subjects': <function Graph.subjects>, 'predicates': <function Graph.predicates>, 'objects': <function Graph.objects>, 'subject_predicates': <function Graph.subject_predicates>, 'subject_objects': <function Graph.subject_objects>, 'predicate_objects': <function Graph.predicate_objects>, 'triples_choices': <function Graph.triples_choices>, 'value': <function Graph.value>, 'items': <function Graph.items>, 'transitiveClosure': <function Graph.transitiveClosure>, 'transitive_objects': <function Graph.transitive_objects>, 'transitive_subjects': <function Graph.transitive_subjects>, 'qname': <function Graph.qname>, 'compute_qname': <function Graph.compute_qname>, 'bind': <function Graph.bind>, 'namespaces': <function Graph.namespaces>, 'absolutize': <function Graph.absolutize>, 'serialize': <function Graph.serialize>, 'print': <function Graph.print>, 'parse': <function Graph.parse>, 'query': <function Graph.query>, 'update': <function Graph.update>, 'n3': <function Graph.n3>, '__reduce__': <function Graph.__reduce__>, 'isomorphic': <function Graph.isomorphic>, 'connected': <function Graph.connected>, 'all_nodes': <function Graph.all_nodes>, 'collection': <function Graph.collection>, 'resource': <function Graph.resource>, '_process_skolem_tuples': <function Graph._process_skolem_tuples>, 'skolemize': <function Graph.skolemize>, 'de_skolemize': <function Graph.de_skolemize>, 'cbd': <function Graph.cbd>, '__dict__': <attribute '__dict__' of 'Graph' objects>, '__weakref__': <attribute '__weakref__' of 'Graph' objects>, '__annotations__': {'__identifier': '_ContextIdentifierType', '__store': 'Store'}})
__eq__(other)[source]

Return self==value.

Return type:

bool

__ge__(other)[source]

Return self>=value.

Parameters:

other (Graph) –

Return type:

bool

__getitem__(item)[source]

A graph can be “sliced” as a shortcut for the triples method The python slice syntax is (ab)used for specifying triples. A generator over matches is returned, the returned tuples include only the parts not given

>>> import rdflib
>>> g = rdflib.Graph()
>>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
[(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]
>>> list(g[:namespace.RDFS.label]) # all label triples
[(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]
>>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
[(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]

Combined with SPARQL paths, more complex queries can be written concisely:

Name of all Bobs friends:

g[bob : FOAF.knows/FOAF.name ]

Some label for Bob:

g[bob : DC.title|FOAF.name|RDFS.label]

All friends and friends of friends of Bob

g[bob : FOAF.knows * “+”]

etc.

New in version 4.0.

__gt__(other)[source]

Return self>value.

Return type:

bool

__hash__()[source]

Return hash(self).

Return type:

int

__iadd__(other)[source]

Add all triples in Graph other to Graph. BNode IDs are not changed.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

__init__(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]
Parameters:
__isub__(other)[source]

Subtract all triples in Graph other from Graph. BNode IDs are not changed.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

__iter__()[source]

Iterates over all triples in the store

Return type:

Generator[Tuple[Node, Node, Node], None, None]

__le__(other)[source]

Return self<=value.

Parameters:

other (Graph) –

Return type:

bool

__len__()[source]

Returns the number of triples in the graph

If context is specified then the number of triples in the context is returned instead.

Return type:

int

__lt__(other)[source]

Return self<value.

Return type:

bool

__module__ = 'rdflib.graph'
__mul__(other)[source]

Set-theoretic intersection. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__or__(other)

Set-theoretic union BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]

__repr__()[source]

Return repr(self).

Return type:

str

__str__()[source]

Return str(self).

Return type:

str

__sub__(other)[source]

Set-theoretic difference. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

__weakref__

list of weak references to the object (if defined)

__xor__(other)[source]

Set-theoretic XOR. BNode IDs are not changed.

Parameters:

other (Graph) –

Return type:

Graph

absolutize(uri, defrag=1)[source]

Turn uri into an absolute URI if it’s not one already

Parameters:
  • uri (str) –

  • defrag (int) –

Return type:

URIRef

add(triple)[source]

Add a triple with self as context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

addN(quads)[source]

Add a sequence of triple with context

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

all_nodes()[source]
Return type:

Set[Node]

bind(prefix, namespace, override=True, replace=False)[source]

Bind prefix to namespace

If override is True will bind namespace to given prefix even if namespace was already bound to a different prefix.

if replace, replace any existing prefix with the new namespace

for example: graph.bind(“foaf”, “http://xmlns.com/foaf/0.1/”)

Parameters:
Return type:

None

cbd(resource, *, target_graph=None)[source]

Retrieves the Concise Bounded Description of a Resource from a Graph

Concise Bounded Description (CBD) is defined in [1] as:

Given a particular node (the starting node) in a particular RDF graph (the source graph), a subgraph of that particular graph, taken to comprise a concise bounded description of the resource denoted by the starting node, can be identified as follows:

  1. Include in the subgraph all statements in the source graph where the subject of the statement is the

    starting node;

  2. Recursively, for all statements identified in the subgraph thus far having a blank node object, include

    in the subgraph all statements in the source graph where the subject of the statement is the blank node in question and which are not already included in the subgraph.

  3. Recursively, for all statements included in the subgraph thus far, for all reifications of each statement

    in the source graph, include the concise bounded description beginning from the rdf:Statement node of each reification.

This results in a subgraph where the object nodes are either URI references, literals, or blank nodes not serving as the subject of any statement in the graph.

[1] https://www.w3.org/Submission/CBD/

Parameters:
  • resource (Node) – a URIRef object, of the Resource for queried for

  • target_graph (Optional[Graph]) – Optionally, a graph to add the CBD to; otherwise, a new graph is created for the CBD

Return type:

Graph

Returns:

a Graph, subgraph of self if no graph was provided otherwise the provided graph

close(commit_pending_transaction=False)[source]

Close the graph store

Might be necessary for stores that require closing a connection to a database or releasing some resource.

Parameters:

commit_pending_transaction (bool) –

Return type:

None

collection(identifier)[source]

Create a new Collection instance.

Parameters:

  • identifier: a URIRef or BNode instance.

Example:

>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> collection = graph.collection(uri)
>>> assert isinstance(collection, Collection)
>>> assert collection.uri is uri
>>> assert collection.graph is graph
>>> collection += [ Literal(1), Literal(2) ]
Parameters:

identifier (Node) –

Return type:

Collection

commit()[source]

Commits active transactions

Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

compute_qname(uri, generate=True)[source]
Parameters:
  • uri (str) –

  • generate (bool) –

Return type:

Tuple[str, URIRef, str]

connected()[source]

Check if the Graph is connected

The Graph is considered undirectional.

Performs a search on the Graph, starting from a random node. Then iteratively goes depth-first through the triplets where the node is subject and object. Return True if all nodes have been visited and False if it cannot continue and there are still unvisited nodes left.

Return type:

bool

de_skolemize(new_graph=None, uriref=None)[source]
Parameters:
Return type:

Graph

destroy(configuration)[source]

Destroy the store identified by configuration if supported

Parameters:
  • self (TypeVar(_GraphT, bound= Graph)) –

  • configuration (str) –

Return type:

TypeVar(_GraphT, bound= Graph)

property identifier: IdentifiedNode
isomorphic(other)[source]

does a very basic check if these graphs are the same If no BNodes are involved, this is accurate.

See rdflib.compare for a correct implementation of isomorphism checks

Parameters:

other (Graph) –

Return type:

bool

items(list)[source]

Generator over all items in the resource specified by list

list is an RDF collection.

Parameters:

list (Node) –

Return type:

Generator[Node, None, None]

n3()[source]

Return an n3 identifier for the Graph

Return type:

str

property namespace_manager: NamespaceManager

this graph’s namespace-manager

namespaces()[source]

Generator over all the prefix, namespace tuples

Return type:

Generator[Tuple[str, URIRef], None, None]

objects(subject=None, predicate=None, unique=False)[source]

A generator of (optionally unique) objects with the given subject and predicate

Parameters:
Return type:

Generator[Node, None, None]

open(configuration, create=False)[source]

Open the graph store

Might be necessary for stores that require opening a connection to a database or acquiring some resource.

Parameters:
  • configuration (str) –

  • create (bool) –

Return type:

Optional[int]

parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]

Parse an RDF source adding the resulting triples to the Graph.

The source is specified using one of source, location, file or data.

Caution

This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with @context directives that point to a network location.

When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Parameters:
  • source (Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath, None]) – An InputSource, file-like object, Path like object, or string. In the case of a string the string is the location of the source.

  • location (Optional[str]) – A string indicating the relative or absolute URL of the source. Graph’s absolutize method is used if a relative location is specified.

  • file (Union[BinaryIO, TextIO, None]) – A file-like object.

  • data (Union[str, bytes, None]) – A string containing the data to be parsed.

  • format (Optional[str]) – Used if format can not be determined from source, e.g. file extension or Media Type. Defaults to text/turtle. Format support can be extended with plugins, but “xml”, “n3” (use for turtle), “nt” & “trix” are built in.

  • publicID (Optional[str]) –

    the logical URI to use as the document base. If None specified the document location is used (at least in the case where there is a document location). This is used as the base URI when resolving relative URIs in the source document, as defined in IETF RFC 3986, given the source document does not define a base URI.

Return type:

Graph

Returns:

self, i.e. the Graph instance.

Examples:

>>> my_data = '''
... <rdf:RDF
...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... >
...   <rdf:Description>
...     <rdfs:label>Example</rdfs:label>
...     <rdfs:comment>This is really just an example.</rdfs:comment>
...   </rdf:Description>
... </rdf:RDF>
... '''
>>> import os, tempfile
>>> fd, file_name = tempfile.mkstemp()
>>> f = os.fdopen(fd, "w")
>>> dummy = f.write(my_data)  # Returns num bytes written
>>> f.close()
>>> g = Graph()
>>> result = g.parse(data=my_data, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> result = g.parse(location=file_name, format="application/rdf+xml")
>>> len(g)
2
>>> g = Graph()
>>> with open(file_name, "r") as f:
...     result = g.parse(f, format="application/rdf+xml")
>>> len(g)
2
>>> os.remove(file_name)
>>> # default turtle parsing
>>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
>>> len(g)
3
Parameters:

args (Any) –

predicate_objects(subject=None, unique=False)[source]

A generator of (optionally unique) (predicate, object) tuples for the given subject

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

predicates(subject=None, object=None, unique=False)[source]

A generator of (optionally unique) predicates with the given subject and object

Parameters:
Return type:

Generator[Node, None, None]

print(format='turtle', encoding='utf-8', out=None)[source]
Parameters:
Return type:

None

qname(uri)[source]
Parameters:

uri (str) –

Return type:

str

query(query_object, processor='sparql', result='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]

Query this graph.

A type of ‘prepared queries’ can be realised by providing initial variable bindings with initBindings

Initial namespaces are used to resolve prefixes used in the query, if none are given, the namespaces from the graph’s namespace manager are used.

Caution

This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in SERVICE directives.

When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Returntype:

Result

Parameters:
Return type:

Result

remove(triple)[source]

Remove a triple from the graph

If the triple does not provide a context attribute, removes the triple from all contexts.

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

resource(identifier)[source]

Create a new Resource instance.

Parameters:

  • identifier: a URIRef or BNode instance.

Example:

>>> graph = Graph()
>>> uri = URIRef("http://example.org/resource")
>>> resource = graph.resource(uri)
>>> assert isinstance(resource, Resource)
>>> assert resource.identifier is uri
>>> assert resource.graph is graph
Parameters:

identifier (Union[Node, str]) –

Return type:

Resource

rollback()[source]

Rollback active transactions

Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

serialize(destination=None, format='turtle', base=None, encoding=None, **args)[source]

Serialize the graph.

Parameters:
  • destination (Union[str, PurePath, IO[bytes], None]) – The destination to serialize the graph to. This can be a path as a str or PurePath object, or it can be a IO[bytes] like object. If this parameter is not supplied the serialized graph will be returned.

  • format (str) – The format that the output should be written in. This value references a Serializer plugin. Format support can be extended with plugins, but "xml", "n3", "turtle", "nt", "pretty-xml", "trix", "trig", "nquads", "json-ld" and "hext" are built in. Defaults to "turtle".

  • base (Optional[str]) – The base IRI for formats that support it. For the turtle format this will be used as the @base directive.

  • encoding (Optional[str]) – Encoding of output.

  • args (Any) – Additional arguments to pass to the Serializer that will be used.

  • self (TypeVar(_GraphT, bound= Graph)) –

Returns:

The serialized graph if destination is None. The serialized graph is returned as str if no encoding is specified, and as bytes if an encoding is specified.

Return type:

bytes if destination is None and encoding is not None.

Return type:

str if destination is None and encoding is None.

Returns:

self (i.e. the Graph instance) if destination is not None.

Return type:

Graph if destination is not None.

set(triple)[source]

Convenience method to update the value of object

Remove any existing triples for subject and predicate before adding (subject, predicate, object).

Parameters:
Return type:

TypeVar(_GraphT, bound= Graph)

skolemize(new_graph=None, bnode=None, authority=None, basepath=None)[source]
Parameters:
Return type:

Graph

property store: Store
subject_objects(predicate=None, unique=False)[source]

A generator of (optionally unique) (subject, object) tuples for the given predicate

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

subject_predicates(object=None, unique=False)[source]

A generator of (optionally unique) (subject, predicate) tuples for the given object

Parameters:
Return type:

Generator[Tuple[Node, Node], None, None]

subjects(predicate=None, object=None, unique=False)[source]

A generator of (optionally unique) subjects with the given predicate and object

Parameters:
Return type:

Generator[Node, None, None]

toPython()[source]
Parameters:

self (TypeVar(_GraphT, bound= Graph)) –

Return type:

TypeVar(_GraphT, bound= Graph)

transitiveClosure(func, arg, seen=None)[source]

Generates transitive closure of a user-defined function against the graph

>>> from rdflib.collection import Collection
>>> g=Graph()
>>> a=BNode("foo")
>>> b=BNode("bar")
>>> c=BNode("baz")
>>> g.add((a,RDF.first,RDF.type)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((a,RDF.rest,b)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b,RDF.first,namespace.RDFS.label)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((b,RDF.rest,c)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c,RDF.first,namespace.RDFS.comment)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((c,RDF.rest,RDF.nil)) 
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> def topList(node,g):
...    for s in g.subjects(RDF.rest, node):
...       yield s
>>> def reverseList(node,g):
...    for f in g.objects(node, RDF.first):
...       print(f)
...    for s in g.subjects(RDF.rest, node):
...       yield s
>>> [rt for rt in g.transitiveClosure(
...     topList,RDF.nil)] 
[rdflib.term.BNode('baz'),
 rdflib.term.BNode('bar'),
 rdflib.term.BNode('foo')]
>>> [rt for rt in g.transitiveClosure(
...     reverseList,RDF.nil)] 
http://www.w3.org/2000/01/rdf-schema#comment
http://www.w3.org/2000/01/rdf-schema#label
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
[rdflib.term.BNode('baz'),
 rdflib.term.BNode('bar'),
 rdflib.term.BNode('foo')]
Parameters:
transitive_objects(subject, predicate, remember=None)[source]

Transitively generate objects for the predicate relationship

Generated objects belong to the depth first transitive closure of the predicate relationship starting at subject.

Parameters:
Return type:

Generator[Optional[Node], None, None]

transitive_subjects(predicate, object, remember=None)[source]

Transitively generate subjects for the predicate relationship

Generated subjects belong to the depth first transitive closure of the predicate relationship starting at object.

Parameters:
Return type:

Generator[Optional[Node], None, None]

triples(triple)[source]

Generator over the triple store

Returns triples that match the given triple pattern. If triple pattern does not provide a context, all contexts will be searched.

Parameters:

triple (Tuple[Optional[Node], Union[Path, Node, None], Optional[Node]]) –

Return type:

Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

triples_choices(triple, context=None)[source]
Parameters:
Return type:

Generator[Tuple[Node, Node, Node], None, None]

update(update_object, processor='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]

Update this graph with the given update query.

Caution

This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in SERVICE directives.

When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.

For information on available security measures, see the RDFLib Security Considerations documentation.

Parameters:
Return type:

None

value(subject=None, predicate=rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#value'), object=None, default=None, any=True)[source]

Get a value for a pair of two criteria

Exactly one of subject, predicate, object must be None. Useful if one knows that there may only be one value.

It is one of those situations that occur a lot, hence this ‘macro’ like utility

Parameters: subject, predicate, object – exactly one must be None default – value to be returned if no values found any – if True, return any value in the case there is more than one, else, raise UniquenessError

Parameters:
Return type:

Optional[Node]

class rdflib.IdentifiedNode(value: str)[source]

Bases: Identifier

An abstract class, primarily defined to identify Nodes that are not Literals.

The name “Identified Node” is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary

__annotations__ = {}
__dict__ = mappingproxy({'__module__': 'rdflib.term', '__doc__': '\n    An abstract class, primarily defined to identify Nodes that are not Literals.\n\n    The name "Identified Node" is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary\n    ', '__getnewargs__': <function IdentifiedNode.__getnewargs__>, 'toPython': <function IdentifiedNode.toPython>, '__dict__': <attribute '__dict__' of 'IdentifiedNode' objects>, '__weakref__': <attribute '__weakref__' of 'IdentifiedNode' objects>, '__annotations__': {}})
__getnewargs__()[source]
Return type:

Tuple[str]

__module__ = 'rdflib.term'
__weakref__

list of weak references to the object (if defined)

toPython()[source]
Return type:

str

class rdflib.Literal(lexical_or_value: Any, lang: str | None = None, datatype: str | None = None, normalize: bool | None = None)[source]

Bases: Identifier

RDF 1.1’s Literals Section: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal

Literals are used for values such as strings, numbers, and dates.

A literal in an RDF graph consists of two or three elements:

  • a lexical form, being a Unicode string, which SHOULD be in Normal Form C

  • a datatype IRI, being an IRI identifying a datatype that determines how the lexical form maps to a literal value, and

  • if and only if the datatype IRI is http://www.w3.org/1999/02/22-rdf-syntax-ns#langString, a non-empty language tag. The language tag MUST be well-formed according to section 2.2.9 of Tags for identifying languages.

A literal is a language-tagged string if the third element is present. Lexical representations of language tags MAY be converted to lower case. The value space of language tags is always in lower case.

For valid XSD datatypes, the lexical form is optionally normalized at construction time. Default behaviour is set by rdflib.NORMALIZE_LITERALS and can be overridden by the normalize parameter to __new__

Equality and hashing of Literals are done based on the lexical form, i.e.:

>>> from rdflib.namespace import XSD
>>> Literal('01') != Literal('1')  # clear - strings differ
True

but with data-type they get normalized:

>>> Literal('01', datatype=XSD.integer) != Literal('1', datatype=XSD.integer)
False

unless disabled:

>>> Literal('01', datatype=XSD.integer, normalize=False) != Literal('1', datatype=XSD.integer)
True

Value based comparison is possible:

>>> Literal('01', datatype=XSD.integer).eq(Literal('1', datatype=XSD.float))
True

The eq method also provides limited support for basic python types:

>>> Literal(1).eq(1) # fine - int compatible with xsd:integer
True
>>> Literal('a').eq('b') # fine - str compatible with plain-lit
False
>>> Literal('a', datatype=XSD.string).eq('a') # fine - str compatible with xsd:string
True
>>> Literal('a').eq(1) # not fine, int incompatible with plain-lit
NotImplemented

Greater-than/less-than ordering comparisons are also done in value space, when compatible datatypes are used. Incompatible datatypes are ordered by DT, or by lang-tag. For other nodes the ordering is None < BNode < URIRef < Literal

Any comparison with non-rdflib Node are “NotImplemented” In PY3 this is an error.

>>> from rdflib import Literal, XSD
>>> lit2006 = Literal('2006-01-01',datatype=XSD.date)
>>> lit2006.toPython()
datetime.date(2006, 1, 1)
>>> lit2006 < Literal('2007-01-01',datatype=XSD.date)
True
>>> Literal(datetime.utcnow()).datatype
rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime')
>>> Literal(1) > Literal(2) # by value
False
>>> Literal(1) > Literal(2.0) # by value
False
>>> Literal('1') > Literal(1) # by DT
True
>>> Literal('1') < Literal('1') # by lexical form
False
>>> Literal('a', lang='en') > Literal('a', lang='fr') # by lang-tag
False
>>> Literal(1) > URIRef('foo') # by node-type
True

The > < operators will eat this NotImplemented and throw a TypeError (py3k):

>>> Literal(1).__gt__(2.0)
NotImplemented
__abs__()[source]
Return type:

Literal

>>> abs(Literal(-1))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> abs( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> abs(Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__add__(val)[source]
>>> from rdflib.namespace import XSD
>>> Literal(1) + 1
rdflib.term.Literal('2', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal("1") + "1"
rdflib.term.Literal('11')

# Handling dateTime/date/time based operations in Literals >>> a = Literal(‘2006-01-01T20:50:00’, datatype=XSD.dateTime) >>> b = Literal(‘P31D’, datatype=XSD.duration) >>> (a + b) rdflib.term.Literal(‘2006-02-01T20:50:00’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#dateTime’)) >>> from rdflib.namespace import XSD >>> a = Literal(‘2006-07-01T20:52:00’, datatype=XSD.dateTime) >>> b = Literal(‘P122DT15H58M’, datatype=XSD.duration) >>> (a + b) rdflib.term.Literal(‘2006-11-01T12:50:00’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#dateTime’))

Parameters:

val (Any) –

Return type:

Literal

__annotations__ = {'_datatype': typing.Optional[rdflib.term.URIRef], '_ill_typed': typing.Optional[bool], '_language': typing.Optional[str], '_value': typing.Any}
__bool__()[source]

Is the Literal “True” This is used for if statements, bool(literal), etc.

Return type:

bool

__eq__(other)[source]

Literals are only equal to other literals.

“Two literals are equal if and only if all of the following hold: * The strings of the two lexical forms compare equal, character by character. * Either both or neither have language tags. * The language tags, if any, compare equal. * Either both or neither have datatype URIs. * The two datatype URIs, if any, compare equal, character by character.” – 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)

>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo"))
True
>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo2"))
False
>>> Literal("1", datatype=URIRef("foo")) == Literal("2", datatype=URIRef("foo"))
False
>>> Literal("1", datatype=URIRef("foo")) == "asdf"
False
>>> from rdflib import XSD
>>> Literal('2007-01-01', datatype=XSD.date) == Literal('2007-01-01', datatype=XSD.date)
True
>>> Literal('2007-01-01', datatype=XSD.date) == date(2007, 1, 1)
False
>>> Literal("one", lang="en") == Literal("one", lang="en")
True
>>> Literal("hast", lang='en') == Literal("hast", lang='de')
False
>>> Literal("1", datatype=XSD.integer) == Literal(1)
True
>>> Literal("1", datatype=XSD.integer) == Literal("01", datatype=XSD.integer)
True
Parameters:

other (Any) –

Return type:

bool

__ge__(other)[source]

Return self>=value.

Parameters:

other (Any) –

Return type:

bool

__getstate__()[source]
Return type:

Tuple[None, Dict[str, Optional[str]]]

__gt__(other)[source]

This implements ordering for Literals, the other comparison methods delegate here

This tries to implement this: http://www.w3.org/TR/sparql11-query/#modOrderBy

In short, Literals with compatible data-types are ordered in value space, i.e. >>> from rdflib import XSD

>>> Literal(1) > Literal(2) # int/int
False
>>> Literal(2.0) > Literal(1) # double/int
True
>>> from decimal import Decimal
>>> Literal(Decimal("3.3")) > Literal(2.0) # decimal/double
True
>>> Literal(Decimal("3.3")) < Literal(4.0) # decimal/double
True
>>> Literal('b') > Literal('a') # plain lit/plain lit
True
>>> Literal('b') > Literal('a', datatype=XSD.string) # plain lit/xsd:str
True

Incompatible datatype mismatches ordered by DT

>>> Literal(1) > Literal("2") # int>string
False

Langtagged literals by lang tag >>> Literal(“a”, lang=”en”) > Literal(“a”, lang=”fr”) False

Parameters:

other (Any) –

Return type:

bool

__hash__()[source]
>>> from rdflib.namespace import XSD
>>> a = {Literal('1', datatype=XSD.integer):'one'}
:rtype: :py:class:`int`
>>> Literal('1', datatype=XSD.double) in a
False

“Called for the key object for dictionary operations, and by the built-in function hash(). Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects.” – 3.4.1 Basic customization (Python)

“Two literals are equal if and only if all of the following hold: * The strings of the two lexical forms compare equal, character by character. * Either both or neither have language tags. * The language tags, if any, compare equal. * Either both or neither have datatype URIs. * The two datatype URIs, if any, compare equal, character by character.” – 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)

__invert__()[source]
Return type:

Literal

>>> ~(Literal(-1))
rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> ~( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))

Not working:

>>> ~(Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__le__(other)[source]
>>> from rdflib.namespace import XSD
>>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
...     ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
True
Parameters:

other (Any) –

Return type:

bool

__lt__(other)[source]

Return self<value.

Parameters:

other (Any) –

Return type:

bool

__module__ = 'rdflib.term'
__neg__()[source]
>>> (- Literal(1))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal(10.5))
rdflib.term.Literal('-10.5', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double'))
>>> from rdflib.namespace import XSD
:rtype: :py:class:`~rdflib.term.Literal`
>>> (- Literal("1", datatype=XSD.integer))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
>>>
static __new__(cls, lexical_or_value, lang=None, datatype=None, normalize=None)[source]
Parameters:
Return type:

Literal

__pos__()[source]
>>> (+ Literal(1))
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal(-1))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
:rtype: :py:class:`~rdflib.term.Literal`
>>> (+ Literal("-1", datatype=XSD.integer))
rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal("1"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal('1')
__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Literal], Tuple[str, Optional[str], Optional[str]]]

__repr__()[source]

Return repr(self).

Return type:

str

__setstate__(arg)[source]
Parameters:

arg (Tuple[Any, Dict[str, Any]]) –

Return type:

None

__slots__ = ('_language', '_datatype', '_value', '_ill_typed')
__sub__(val)[source]
>>> from rdflib.namespace import XSD
>>> Literal(2) - 1
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal(1.1) - 1.0
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double'))
>>> Literal(1.1) - 1
rdflib.term.Literal('0.1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#decimal'))
>>> Literal(1.1, datatype=XSD.float) - Literal(1.0, datatype=XSD.float)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#float'))
>>> Literal("1.1") - 1.0 
Traceback (most recent call last):
...
TypeError: Not a number; rdflib.term.Literal('1.1')
>>> Literal(1.1, datatype=XSD.integer) - Literal(1.0, datatype=XSD.integer)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))

# Handling dateTime/date/time based operations in Literals >>> a = Literal(‘2006-01-01T20:50:00’, datatype=XSD.dateTime) >>> b = Literal(‘2006-02-01T20:50:00’, datatype=XSD.dateTime) >>> (b - a) rdflib.term.Literal(‘P31D’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’)) >>> from rdflib.namespace import XSD >>> a = Literal(‘2006-07-01T20:52:00’, datatype=XSD.dateTime) >>> b = Literal(‘2006-11-01T12:50:00’, datatype=XSD.dateTime) >>> (a - b) rdflib.term.Literal(‘-P122DT15H58M’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’)) >>> (b - a) rdflib.term.Literal(‘P122DT15H58M’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#duration’))

Parameters:

val (Any) –

Return type:

Literal

property datatype: URIRef | None
eq(other)[source]

Compare the value of this literal with something else

Either, with the value of another literal comparisons are then done in literal “value space”, and according to the rules of XSD subtype-substitution/type-promotion

OR, with a python object:

basestring objects can be compared with plain-literals, or those with datatype xsd:string

bool objects with xsd:boolean

a int, long or float with numeric xsd types

isodate date,time,datetime objects with xsd:date,xsd:time or xsd:datetime

Any other operations returns NotImplemented

Parameters:

other (Any) –

Return type:

bool

property ill_typed: bool | None

For recognized datatype IRIs, this value will be True if the literal is ill formed, otherwise it will be False. Literal.value (i.e. the literal value) should always be defined if this property is False, but should not be considered reliable if this property is True.

If the literal’s datatype is None or not in the set of recognized datatype IRIs this value will be None.

property language: str | None
n3(namespace_manager=None)[source]

Returns a representation in the N3 format.

Examples:

>>> Literal("foo").n3()
'"foo"'

Strings with newlines or triple-quotes:

>>> Literal("foo\nbar").n3()
'"""foo\nbar"""'

>>> Literal("''\'").n3()
'"\'\'\'"'

>>> Literal('"""').n3()
'"\\"\\"\\""'

Language:

>>> Literal("hello", lang="en").n3()
'"hello"@en'

Datatypes:

>>> Literal(1).n3()
'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

>>> Literal(1.0).n3()
'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'

>>> Literal(True).n3()
'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'

Datatype and language isn’t allowed (datatype takes precedence):

>>> Literal(1, lang="en").n3()
'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

Custom datatype:

>>> footype = URIRef("http://example.org/ns#foo")
>>> Literal("1", datatype=footype).n3()
'"1"^^<http://example.org/ns#foo>'

Passing a namespace-manager will use it to abbreviate datatype URIs:

>>> from rdflib import Graph
>>> Literal(1).n3(Graph().namespace_manager)
'"1"^^xsd:integer'
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

neq(other)[source]

A “semantic”/interpreted not equal function, by default, same as __ne__

Parameters:

other (Any) –

Return type:

bool

normalize()[source]

Returns a new literal with a normalised lexical representation of this literal >>> from rdflib import XSD >>> Literal(“01”, datatype=XSD.integer, normalize=False).normalize() rdflib.term.Literal(‘1’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

Illegal lexical forms for the datatype given are simply passed on >>> Literal(“a”, datatype=XSD.integer, normalize=False) rdflib.term.Literal(‘a’, datatype=rdflib.term.URIRef(’http://www.w3.org/2001/XMLSchema#integer’))

Return type:

Literal

toPython()[source]

Returns an appropriate python datatype derived from this RDF Literal

Return type:

Any

property value: Any
rdflib.NORMALIZE_LITERALS = True

If True - Literals lexical forms are normalized when created. I.e. the lexical forms is parsed according to data-type, then the stored lexical form is the re-serialized value that was parsed.

Illegal values for a datatype are simply kept. The normalized keyword for Literal.__new__ can override this.

For example:

>>> from rdflib import Literal,XSD
>>> Literal("01", datatype=XSD.int)
rdflib.term.Literal("1", datatype=rdflib.term.URIRef("http://www.w3.org/2001/XMLSchema#integer"))

This flag may be changed at any time, but will only affect literals created after that time, previously created literals will remain (un)normalized.

class rdflib.Namespace(value: str | bytes)[source]

Bases: str

Utility class for quickly generating URIRefs with a common prefix

>>> from rdflib.namespace import Namespace
>>> n = Namespace("http://example.org/")
>>> n.Person # as attribute
rdflib.term.URIRef('http://example.org/Person')
>>> n['first-name'] # as item - for things that are not valid python identifiers
rdflib.term.URIRef('http://example.org/first-name')
>>> n.Person in n
True
>>> n2 = Namespace("http://example2.org/")
>>> n.Person in n2
False
__contains__(ref)[source]

Allows to check if a URI is within (starts with) this Namespace.

>>> from rdflib import URIRef
>>> namespace = Namespace('http://example.org/')
>>> uri = URIRef('http://example.org/foo')
>>> uri in namespace
True
>>> person_class = namespace['Person']
>>> person_class in namespace
True
>>> obj = URIRef('http://not.example.org/bar')
>>> obj in namespace
False
Parameters:

ref (str) –

Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.namespace', '__doc__': '\n    Utility class for quickly generating URIRefs with a common prefix\n\n    >>> from rdflib.namespace import Namespace\n    >>> n = Namespace("http://example.org/")\n    >>> n.Person # as attribute\n    rdflib.term.URIRef(\'http://example.org/Person\')\n    >>> n[\'first-name\'] # as item - for things that are not valid python identifiers\n    rdflib.term.URIRef(\'http://example.org/first-name\')\n    >>> n.Person in n\n    True\n    >>> n2 = Namespace("http://example2.org/")\n    >>> n.Person in n2\n    False\n    ', '__new__': <staticmethod object>, 'title': <property object>, 'term': <function Namespace.term>, '__getitem__': <function Namespace.__getitem__>, '__getattr__': <function Namespace.__getattr__>, '__repr__': <function Namespace.__repr__>, '__contains__': <function Namespace.__contains__>, '__dict__': <attribute '__dict__' of 'Namespace' objects>, '__weakref__': <attribute '__weakref__' of 'Namespace' objects>, '__annotations__': {}})
__getattr__(name)[source]
Parameters:

name (str) –

Return type:

URIRef

__getitem__(key)[source]

Return self[key].

Parameters:

key (str) –

Return type:

URIRef

__module__ = 'rdflib.namespace'
static __new__(cls, value)[source]
Parameters:

value (Union[str, bytes]) –

Return type:

Namespace

__repr__()[source]

Return repr(self).

Return type:

str

__weakref__

list of weak references to the object (if defined)

term(name)[source]
Parameters:

name (str) –

Return type:

URIRef

property title: URIRef

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

class rdflib.URIRef(value: str, base: str | None = None)[source]

Bases: IdentifiedNode

RDF 1.1’s IRI Section https://www.w3.org/TR/rdf11-concepts/#section-IRIs

Note

Documentation on RDF outside of RDFLib uses the term IRI or URI whereas this class is called URIRef. This is because it was made when the first version of the RDF specification was current, and it used the term URIRef, see RDF 1.0 URIRef

An IRI (Internationalized Resource Identifier) within an RDF graph is a Unicode string that conforms to the syntax defined in RFC 3987.

IRIs in the RDF abstract syntax MUST be absolute, and MAY contain a fragment identifier.

IRIs are a generalization of URIs [RFC3986] that permits a wider range of Unicode characters.

__add__(other)[source]

Return self+value.

Return type:

URIRef

__annotations__ = {'__invert__': typing.Callable[[ForwardRef('URIRef')], ForwardRef('InvPath')], '__neg__': typing.Callable[[ForwardRef('URIRef')], ForwardRef('NegatedPath')], '__or__': typing.Callable[[ForwardRef('URIRef'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('AlternativePath')], '__truediv__': typing.Callable[[ForwardRef('URIRef'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('SequencePath')]}
__invert__()

inverse path

Parameters:

p (Union[URIRef, Path]) –

Return type:

InvPath

__mod__(other)[source]

Return self%value.

Return type:

URIRef

__module__ = 'rdflib.term'
__mul__(mul)

cardinality path

Parameters:
Return type:

MulPath

__neg__()

negated path

Parameters:

p (Union[URIRef, AlternativePath, InvPath]) –

Return type:

NegatedPath

static __new__(cls, value, base=None)[source]
Parameters:
Return type:

URIRef

__or__(other)

alternative path

Parameters:
__radd__(other)[source]
Return type:

URIRef

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[URIRef], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
__truediv__(other)

sequence path

Parameters:
de_skolemize()[source]

Create a Blank Node from a skolem URI, in accordance with http://www.w3.org/TR/rdf11-concepts/#section-skolemization. This function accepts only rdflib type skolemization, to provide a round-tripping within the system. :rtype: BNode

New in version 4.0.

defrag()[source]
Return type:

URIRef

property fragment: str

Return the URL Fragment

>>> URIRef("http://example.com/some/path/#some-fragment").fragment
'some-fragment'
>>> URIRef("http://example.com/some/path/").fragment
''
n3(namespace_manager=None)[source]

This will do a limited check for valid URIs, essentially just making sure that the string includes no illegal characters (<, >, ", {, }, |, \, `, ^)

Parameters:

namespace_manager (Optional[NamespaceManager]) – if not None, will be used to make up a prefixed name

Return type:

str

class rdflib.Variable(value: str)[source]

Bases: Identifier

A Variable - this is used for querying, or in Formula aware graphs, where Variables can be stored

__annotations__ = {}
__module__ = 'rdflib.term'
static __new__(cls, value)[source]
Parameters:

value (str) –

Return type:

Variable

__reduce__()[source]

Helper for pickle.

Return type:

Tuple[Type[Variable], Tuple[str]]

__repr__()[source]

Return repr(self).

Return type:

str

__slots__ = ()
n3(namespace_manager=None)[source]
Parameters:

namespace_manager (Optional[NamespaceManager]) –

Return type:

str

toPython()[source]
Return type:

str