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.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
__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
__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.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

__iadd__(other)[source]
__init__(graph, uri, seq=[])[source]
__iter__()[source]

Iterator over items in Collections

__len__()[source]

length of items in collection.

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

TODO

__weakref__

list of weak references to the object (if defined)

append(item)[source]
>>> 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
clear()[source]
index(item)[source]

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

n3()[source]
>>> 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>
  "2"^^<http://www.w3.org/2001/XMLSchema#integer>
  "3"^^<http://www.w3.org/2001/XMLSchema#integer> )

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.

__dict__ = mappingproxy({'__module__': 'rdflib.events', '__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>, '__annotations__': {}})
__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]
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.

__init__(msg=None)[source]
__module__ = 'rdflib.exceptions'
__weakref__

list of weak references to the object (if defined)

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

Bases: Error

RDF Parser error.

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

Return str(self).

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], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], 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.

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root 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: Union[Tuple[Optional[Node], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], Optional[Node], Optional[Graph]]], context: Optional[Graph] = None) Generator[Tuple[Node, Node, Node], None, None][source]
triples(triple_or_quad: Union[Tuple[Optional[Node], Path, Optional[Node]], Tuple[Optional[Node], Path, Optional[Node], Optional[Graph]]], context: Optional[Graph] = None) Generator[Tuple[Node, Path, Node], None, None]
triples(triple_or_quad: Union[Tuple[Optional[Node], Optional[Union[Path, Node]], Optional[Node]], Tuple[Optional[Node], Optional[Union[Path, Node]], Optional[Node], Optional[Graph]]], context: Optional[Graph] = None) Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

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 source adding the resulting triples to its own context (sub graph of this graph).

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

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root 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='core')[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], Optional[Node], 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='core')[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)[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

Return type:

Graph

Returns:

a Graph, subgraph of self

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
Return type:

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

Return type:

NamespaceManager

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.

Parameters:
  • source: An InputSource, file-like object, or string. In the case of a string the string is the location of the source.

  • location: A string indicating the relative or absolute URL of the source. Graph’s absolutize method is used if a relative location is specified.

  • file: A file-like object.

  • data: A string containing the data to be parsed.

  • format: 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: 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).

Returns:
  • self, 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:
Return type:

Graph

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.

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: str, base: Optional[str], encoding: str, **args: Any) bytes[source]
serialize(destination: None = None, format: str = 'turtle', base: Optional[str] = None, *, encoding: str, **args: Any) bytes
serialize(destination: None = None, format: str = 'turtle', base: Optional[str] = None, encoding: None = None, **args: Any) str
serialize(destination: Union[str, PurePath, IO[bytes]], format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) Graph
serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = None, format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) Union[bytes, str, Graph]

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
Return type:

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: Tuple[Optional[Node], Optional[Node], Optional[Node]]) Generator[Tuple[Node, Node, Node], None, None][source]
triples(triple: Tuple[Optional[Node], Path, Optional[Node]]) Generator[Tuple[Node, Path, Node], None, None]
triples(triple: Tuple[Optional[Node], Optional[Union[Path, Node]], Optional[Node]]) Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

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.

Parameters:
Return type:

None

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

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], Optional[Node], Optional[Node]], Tuple[Optional[Node], Optional[Node], 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.

Returns:

The graph into which the source was parsed. In the case of n3 it returns the root 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: Tuple[Optional[Node], Optional[Node], Optional[Node]]) Generator[Tuple[Node, Node, Node], None, None][source]
triples(triple: Tuple[Optional[Node], Path, Optional[Node]]) Generator[Tuple[Node, Path, Node], None, None]
triples(triple: Tuple[Optional[Node], Optional[Union[Path, Node]], Optional[Node]]) Generator[Union[Tuple[Node, Node, Node], Tuple[Node, Path, Node]], None, None]

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).

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

Bases: InputSource, object

TODO:

Parameters:

system_id (Optional[str]) –

__init__(system_id=None)[source]
Parameters:

system_id (Optional[str]) –

__module__ = 'rdflib.parser'
close()[source]
class rdflib.parser.Parser[source]

Bases: object

__init__()[source]
__module__ = 'rdflib.parser'
__slots__ = ()
parse(source, sink)[source]
Parameters:
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
__init__(data, system_id=None)[source]
__module__ = 'rdflib.parser'
close()[source]
content_type: Optional[str]
getPublicId()[source]

Returns the public identifier of this InputSource.

getSystemId()[source]

Returns the system identifier of this InputSource.

setPublicId(public_id)[source]

Sets the public identifier of this InputSource.

setSystemId(system_id)[source]

Sets the system identifier of this InputSource.

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': typing.List[str]}
__init__(system_id=None, format=None)[source]
Parameters:
__module__ = 'rdflib.parser'
__repr__()[source]

Return repr(self).

get_alternates(type_=None)[source]
Parameters:

type_ (Optional[str]) –

Return type:

List[str]

Parameters:

response (HTTPResponse) –

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

message (HTTPMessage) –

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

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

Return repr(self).

eval(graph, subj=None, obj=None)[source]
n3()[source]
class rdflib.paths.InvPath(arg)[source]

Bases: Path

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

Return repr(self).

eval(graph, subj=None, obj=None)[source]
n3()[source]
class rdflib.paths.MulPath(path, mod)[source]

Bases: Path

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

Return repr(self).

eval(graph, subj=None, obj=None, first=True)[source]
n3()[source]
class rdflib.paths.NegatedPath(arg)[source]

Bases: Path

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

Return repr(self).

eval(graph, subj=None, obj=None)[source]
n3()[source]
class rdflib.paths.Path[source]

Bases: object

__annotations__ = {'__invert__': typing.Callable[[ForwardRef('Path')], ForwardRef('InvPath')], '__mul__': typing.Callable[[ForwardRef('Path'), str], ForwardRef('MulPath')], '__neg__': typing.Callable[[ForwardRef('Path')], ForwardRef('NegatedPath')], '__or__': typing.Callable[[ForwardRef('Path'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('AlternativePath')], '__truediv__': typing.Callable[[ForwardRef('Path'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('SequencePath')]}
__dict__ = mappingproxy({'__module__': 'rdflib.paths', '__annotations__': {'__or__': typing.Callable[[ForwardRef('Path'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('AlternativePath')], '__invert__': typing.Callable[[ForwardRef('Path')], ForwardRef('InvPath')], '__neg__': typing.Callable[[ForwardRef('Path')], ForwardRef('NegatedPath')], '__truediv__': typing.Callable[[ForwardRef('Path'), typing.Union[ForwardRef('URIRef'), ForwardRef('Path')]], ForwardRef('SequencePath')], '__mul__': typing.Callable[[ForwardRef('Path'), str], ForwardRef('MulPath')]}, 'eval': <function Path.eval>, '__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>})
__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).

__invert__()

inverse path

__le__(other, NotImplemented=NotImplemented)

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

__lt__(other)[source]

Return self<value.

__module__ = 'rdflib.paths'
__mul__(mul)

cardinality path

__neg__()

negated path

__or__(other)

alternative path

__truediv__(other)

sequence path

__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

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

Return repr(self).

eval(graph, subj=None, obj=None)[source]
n3()[source]
rdflib.paths.evalPath(graph, t)[source]
rdflib.paths.eval_path(graph, t)[source]
rdflib.paths.inv_path(p)[source]

inverse path

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

cardinality path

rdflib.paths.neg_path(p)[source]

negated path

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

alternative path

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

sequence path

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

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

A generic type variable for plugins

alias of TypeVar(‘PluginT’)

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: Optional[str] = None, kind: Type[PluginT] = None) Iterator[Plugin[PluginT]][source]
rdflib.plugin.plugins(name: Optional[str] = None, kind: None = None) Iterator[Plugin]

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

Return type:

MutableSequence[Mapping[Variable, Identifier]]

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: str, default: Identifier) Identifier[source]
get(name: str, default: Optional[Identifier] = None) Optional[Identifier]
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

Serializer plugin interface.

This module is useful for those wanting to write a serializer that can plugin to rdflib. If you are wanting to invoke a serializer you likely want to do so through the Graph class serialize method.

TODO: info for how to write a serializer that can plugin to rdflib. See also rdflib.plugin

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 (str) –

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'}