rdflib package¶
Subpackages¶
- rdflib.extras package
- Submodules
- rdflib.extras.cmdlineutils module
- rdflib.extras.describer module
- rdflib.extras.external_graph_libs module
- rdflib.extras.infixowl module
AllClasses()
AllDifferent()
AllProperties()
AnnotatableTerms
BooleanClass
Callable
CastClass()
Class
Class.__and__()
Class.__eq__()
Class.__hash__()
Class.__iadd__()
Class.__init__()
Class.__invert__()
Class.__isub__()
Class.__module__
Class.__or__()
Class.__repr__()
Class.annotation
Class.complementOf
Class.disjointWith
Class.equivalentClass
Class.extent
Class.extentQuery
Class.isPrimitive()
Class.parents
Class.serialize()
Class.setupNounAnnotations()
Class.subClassOf
Class.subSumpteeIds()
ClassNamespaceFactory
CommonNSBindings()
ComponentTerms()
DeepClassClear()
EnumeratedClass
GetIdentifiedClasses()
Individual
Infix
MalformedClass
MalformedClassError
OWLRDFListProxy
OWLRDFListProxy.__contains__()
OWLRDFListProxy.__delitem__()
OWLRDFListProxy.__dict__
OWLRDFListProxy.__eq__()
OWLRDFListProxy.__getitem__()
OWLRDFListProxy.__hash__
OWLRDFListProxy.__iadd__()
OWLRDFListProxy.__init__()
OWLRDFListProxy.__iter__()
OWLRDFListProxy.__len__()
OWLRDFListProxy.__module__
OWLRDFListProxy.__setitem__()
OWLRDFListProxy.__weakref__
OWLRDFListProxy.append()
OWLRDFListProxy.clear()
OWLRDFListProxy.index()
Ontology
Property
Restriction
Restriction.__eq__()
Restriction.__hash__()
Restriction.__init__()
Restriction.__module__
Restriction.__repr__()
Restriction.allValuesFrom
Restriction.cardinality
Restriction.hasValue
Restriction.isPrimitive()
Restriction.maxCardinality
Restriction.minCardinality
Restriction.onProperty
Restriction.restrictionKind()
Restriction.restrictionKinds
Restriction.serialize()
Restriction.someValuesFrom
classOrIdentifier()
classOrTerm()
generateQName()
manchesterSyntax()
propertyOrIdentifier()
- Module contents
- rdflib.namespace package
- Module contents
- Namespace Utilities
ClosedNamespace
DefinedNamespace
Namespace
NamespaceManager
NamespaceManager.__contains__()
NamespaceManager.__dict__
NamespaceManager.__init__()
NamespaceManager.__module__
NamespaceManager.__weakref__
NamespaceManager.absolutize()
NamespaceManager.bind()
NamespaceManager.compute_qname()
NamespaceManager.compute_qname_strict()
NamespaceManager.expand_curie()
NamespaceManager.namespaces()
NamespaceManager.normalizeUri()
NamespaceManager.qname()
NamespaceManager.qname_strict()
NamespaceManager.reset()
NamespaceManager.store
is_ncname()
split_uri()
- Module contents
- rdflib.plugins package
- Subpackages
- rdflib.plugins.parsers package
- Submodules
- rdflib.plugins.parsers.RDFVOC module
- rdflib.plugins.parsers.hext module
- rdflib.plugins.parsers.jsonld module
- rdflib.plugins.parsers.notation3 module
- rdflib.plugins.parsers.nquads module
- rdflib.plugins.parsers.ntriples module
- rdflib.plugins.parsers.rdfxml module
- rdflib.plugins.parsers.trig module
- rdflib.plugins.parsers.trix module
- Module contents
- rdflib.plugins.serializers package
- Submodules
- rdflib.plugins.serializers.hext module
- rdflib.plugins.serializers.jsonld module
- rdflib.plugins.serializers.longturtle module
- rdflib.plugins.serializers.n3 module
- rdflib.plugins.serializers.nquads module
- rdflib.plugins.serializers.nt module
- rdflib.plugins.serializers.rdfxml module
- rdflib.plugins.serializers.trig module
- rdflib.plugins.serializers.trix module
- rdflib.plugins.serializers.turtle module
- rdflib.plugins.serializers.xmlwriter module
- Module contents
- rdflib.plugins.shared package
- rdflib.plugins.sparql package
- Subpackages
- Submodules
- rdflib.plugins.sparql.aggregates module
- rdflib.plugins.sparql.algebra module
- rdflib.plugins.sparql.datatypes module
- rdflib.plugins.sparql.evaluate module
- rdflib.plugins.sparql.evalutils module
- rdflib.plugins.sparql.operators module
- rdflib.plugins.sparql.parser module
- rdflib.plugins.sparql.parserutils module
- rdflib.plugins.sparql.processor module
- rdflib.plugins.sparql.sparql module
- rdflib.plugins.sparql.update module
- Module contents
- rdflib.plugins.stores package
- Submodules
- rdflib.plugins.stores.auditable module
- rdflib.plugins.stores.berkeleydb module
- rdflib.plugins.stores.concurrent module
- rdflib.plugins.stores.memory module
- rdflib.plugins.stores.regexmatching module
- rdflib.plugins.stores.sparqlconnector module
- rdflib.plugins.stores.sparqlstore module
- Module contents
- rdflib.plugins.parsers package
- Module contents
- Subpackages
- rdflib.tools package
- Submodules
- rdflib.tools.chunk_serializer module
- rdflib.tools.csv2rdf module
- rdflib.tools.defined_namespace_creator module
- rdflib.tools.graphisomorphism module
IsomorphicTestableGraph
IsomorphicTestableGraph.__eq__()
IsomorphicTestableGraph.__hash__
IsomorphicTestableGraph.__init__()
IsomorphicTestableGraph.__module__
IsomorphicTestableGraph.__ne__()
IsomorphicTestableGraph.hashtriples()
IsomorphicTestableGraph.internal_hash()
IsomorphicTestableGraph.vhash()
IsomorphicTestableGraph.vhashtriple()
IsomorphicTestableGraph.vhashtriples()
main()
- rdflib.tools.rdf2dot module
- rdflib.tools.rdfpipe module
- rdflib.tools.rdfs2dot module
- Module contents
Submodules¶
rdflib.collection module¶
- class rdflib.collection.Collection(graph, uri, seq=[])[source]¶
Bases:
object
See “Emulating container types”: https://docs.python.org/reference/datamodel.html#emulating-container-types
>>> from rdflib.term import Literal >>> from rdflib.graph import Graph >>> from pprint import pprint >>> listname = BNode() >>> g = Graph('Memory') >>> listItem1 = BNode() >>> listItem2 = BNode() >>> g.add((listname, RDF.first, Literal(1))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listname, RDF.rest, listItem1)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem1, RDF.first, Literal(2))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem1, RDF.rest, listItem2)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem2, RDF.rest, RDF.nil)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem2, RDF.first, Literal(3))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> c = Collection(g,listname) >>> pprint([term.n3() for term in c]) [u'"1"^^<http://www.w3.org/2001/XMLSchema#integer>', u'"2"^^<http://www.w3.org/2001/XMLSchema#integer>', u'"3"^^<http://www.w3.org/2001/XMLSchema#integer>']
>>> Literal(1) in c True >>> len(c) 3 >>> c._get_container(1) == listItem1 True >>> c.index(Literal(2)) == 1 True
- __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.term import Literal\n >>> from rdflib.graph import Graph\n >>> from pprint import pprint\n >>> listname = BNode()\n >>> g = Graph(\'Memory\')\n >>> listItem1 = BNode()\n >>> listItem2 = BNode()\n >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS\n <Graph identifier=... (<class \'rdflib.graph.Graph\'>)>\n >>> c = Collection(g,listname)\n >>> pprint([term.n3() for term in c])\n [u\'"1"^^<http://www.w3.org/2001/XMLSchema#integer>\',\n u\'"2"^^<http://www.w3.org/2001/XMLSchema#integer>\',\n u\'"3"^^<http://www.w3.org/2001/XMLSchema#integer>\']\n\n >>> Literal(1) in c\n True\n >>> len(c)\n 3\n >>> c._get_container(1) == listItem1\n True\n >>> c.index(Literal(2)) == 1\n True\n ', '__init__': <function Collection.__init__>, 'n3': <function Collection.n3>, '_get_container': <function Collection._get_container>, '__len__': <function Collection.__len__>, 'index': <function Collection.index>, '__getitem__': <function Collection.__getitem__>, '__setitem__': <function Collection.__setitem__>, '__delitem__': <function Collection.__delitem__>, '__iter__': <function Collection.__iter__>, '_end': <function Collection._end>, 'append': <function Collection.append>, '__iadd__': <function Collection.__iadd__>, 'clear': <function Collection.clear>, '__dict__': <attribute '__dict__' of 'Collection' objects>, '__weakref__': <attribute '__weakref__' of 'Collection' objects>, '__annotations__': {}})¶
- __module__ = 'rdflib.collection'¶
- __weakref__¶
list of weak references to the object (if defined)
- append(item)[source]¶
>>> from rdflib.term import Literal >>> from rdflib.graph import Graph >>> listname = BNode() >>> g = Graph() >>> c = Collection(g,listname,[Literal(1),Literal(2)]) >>> links = [ ... list(g.subjects(object=i, predicate=RDF.first))[0] for i in c] >>> len([i for i in links if (i, RDF.rest, RDF.nil) in g]) 1
- Parameters:
item (
Node
) –- Return type:
- n3()[source]¶
>>> from rdflib.term import Literal >>> from rdflib.graph import Graph >>> listname = BNode() >>> g = Graph('Memory') >>> listItem1 = BNode() >>> listItem2 = BNode() >>> g.add((listname, RDF.first, Literal(1))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listname, RDF.rest, listItem1)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem1, RDF.first, Literal(2))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem1, RDF.rest, listItem2)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem2, RDF.rest, RDF.nil)) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g.add((listItem2, RDF.first, Literal(3))) <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> c = Collection(g, listname) >>> print(c.n3()) ( "1"^^<http://www.w3.org/2001/XMLSchema#integer> :rtype: :py:class:`str`
rdflib.compare module¶
A collection of utilities for canonicalizing and inspecting graphs.
Among other things, they solve of the problem of deterministic bnode comparisons.
Warning: the time to canonicalize bnodes may increase exponentially on degenerate larger graphs. Use with care!
Example of comparing two graphs:
>>> g1 = Graph().parse(format='n3', data='''
... @prefix : <http://example.org/ns#> .
... <http://example.org> :rel
... <http://example.org/same>,
... [ :label "Same" ],
... <http://example.org/a>,
... [ :label "A" ] .
... ''')
>>> g2 = Graph().parse(format='n3', data='''
... @prefix : <http://example.org/ns#> .
... <http://example.org> :rel
... <http://example.org/same>,
... [ :label "Same" ],
... <http://example.org/b>,
... [ :label "B" ] .
... ''')
>>>
>>> iso1 = to_isomorphic(g1)
>>> iso2 = to_isomorphic(g2)
These are not isomorphic:
>>> iso1 == iso2
False
Diff the two graphs:
>>> in_both, in_first, in_second = graph_diff(iso1, iso2)
Present in both:
>>> def dump_nt_sorted(g):
... for l in sorted(g.serialize(format='nt').splitlines()):
... if l: print(l.decode('ascii'))
>>> dump_nt_sorted(in_both)
<http://example.org>
<http://example.org/ns#rel> <http://example.org/same> .
<http://example.org>
<http://example.org/ns#rel> _:cbcaabaaba17fecbc304a64f8edee4335e .
_:cbcaabaaba17fecbc304a64f8edee4335e
<http://example.org/ns#label> "Same" .
Only in first:
>>> dump_nt_sorted(in_first)
<http://example.org>
<http://example.org/ns#rel> <http://example.org/a> .
<http://example.org>
<http://example.org/ns#rel> _:cb124e4c6da0579f810c0ffe4eff485bd9 .
_:cb124e4c6da0579f810c0ffe4eff485bd9
<http://example.org/ns#label> "A" .
Only in second:
>>> dump_nt_sorted(in_second)
<http://example.org>
<http://example.org/ns#rel> <http://example.org/b> .
<http://example.org>
<http://example.org/ns#rel> _:cb558f30e21ddfc05ca53108348338ade8 .
_:cb558f30e21ddfc05ca53108348338ade8
<http://example.org/ns#label> "B" .
- class rdflib.compare.IsomorphicGraph(**kwargs)[source]¶
Bases:
ConjunctiveGraph
An implementation of the RGDA1 graph digest algorithm.
An implementation of RGDA1 (publication below), a combination of Sayers & Karp’s graph digest algorithm using sum and SHA-256 <http://www.hpl.hp.com/techreports/2003/HPL-2003-235R1.pdf> and traces <http://pallini.di.uniroma1.it>, an average case polynomial time algorithm for graph canonicalization.
McCusker, J. P. (2015). WebSig: A Digital Signature Framework for the Web. Rensselaer Polytechnic Institute, Troy, NY. http://gradworks.umi.com/3727015.pdf
- __module__ = 'rdflib.compare'¶
- rdflib.compare.graph_diff(g1, g2)[source]¶
Returns three sets of triples: “in both”, “in first” and “in second”.
- 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
- 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
.
- 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.
rdflib.compat module¶
Utility functions and objects to ease Python 2/3 compatibility, and different versions of support libraries.
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'¶
- 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" .
- __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__': {}})¶
- __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”
- __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)
- exception rdflib.container.NoElementException(message='rdf:Alt Container is empty')[source]¶
Bases:
Exception
- __module__ = 'rdflib.container'¶
- __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'¶
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)
- 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__': {}})¶
- __module__ = 'rdflib.events'¶
- __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.
- __module__ = 'rdflib.exceptions'¶
- __weakref__¶
list of weak references to the object (if defined)
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
- __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__': {}})¶
- __module__ = 'rdflib.graph'¶
- __weakref__¶
list of weak references to the object (if defined)
- 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:
- __module__ = 'rdflib.graph'¶
- 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
- contexts(triple=None)[source]¶
Iterate over all contexts in the graph
If triple is specified, iterate over all contexts the triple is in.
- get_context(identifier, quoted=False, base=None)[source]¶
Return a context graph for the given identifier
identifier must be a URIRef or BNode.
- get_graph(identifier)[source]¶
Returns the graph identified by given identifier
- Parameters:
identifier (
IdentifiedNode
) –- Return type:
- 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.
Caution
This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with
@context
directives that point to a network location.When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- 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
- triples(triple_or_quad, context=None)[source]¶
Iterate over all the triples in the entire conjunctive graph
For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.
- 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.
- __module__ = 'rdflib.graph'¶
- contexts(triple=None)[source]¶
Iterate over all contexts in the graph
If triple is specified, iterate over all contexts the triple is in.
- graphs(triple=None)¶
Iterate over all contexts in the graph
If triple is specified, iterate over all contexts the triple is in.
- parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]¶
Caution
This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with
@context
directives that point to a network location.When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- class rdflib.graph.Graph(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]¶
Bases:
Node
An RDF Graph
The constructor accepts one argument, the “store” that will be used to store the graph data (see the “store” package for stores currently shipped with rdflib).
Stores can be context-aware or unaware. Unaware stores take up (some) less space but cannot support features that require context, such as true merging/demerging of sub-graphs and provenance.
Even if used with a context-aware store, Graph will only expose the quads which belong to the default graph. To access the rest of the data, ConjunctiveGraph or Dataset classes can be used instead.
The Graph constructor can take an identifier which identifies the Graph by name. If none is given, the graph is assigned a BNode for its identifier.
For more on named graphs, see: http://www.w3.org/2004/03/trix/
- Parameters:
- __and__(other)¶
Set-theoretic intersection. BNode IDs are not changed.
- __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'}})¶
- __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.
- __init__(store='default', identifier=None, namespace_manager=None, base=None, bind_namespaces='rdflib')[source]¶
- __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:
- __module__ = 'rdflib.graph'¶
- __or__(other)¶
Set-theoretic union BNode IDs are not changed.
- __weakref__¶
list of weak references to the object (if defined)
- 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/”)
- 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:
- Include in the subgraph all statements in the source graph where the subject of the statement is the
starting node;
- 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.
- 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.
- 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.
- 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:
- 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:
- property identifier: IdentifiedNode¶
- isomorphic(other)[source]¶
does a very basic check if these graphs are the same If no BNodes are involved, this is accurate.
See rdflib.compare for a correct implementation of isomorphism checks
- items(list)[source]¶
Generator over all items in the resource specified by list
list is an RDF collection.
- property namespace_manager: NamespaceManager¶
this graph’s namespace-manager
- objects(subject=None, predicate=None, unique=False)[source]¶
A generator of (optionally unique) objects with the given subject and predicate
- 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.
- parse(source=None, publicID=None, format=None, location=None, file=None, data=None, **args)[source]¶
Parse an RDF source adding the resulting triples to the Graph.
The source is specified using one of source, location, file or data.
Caution
This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with
@context
directives that point to a network location.When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- Parameters:
source
: 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
- predicate_objects(subject=None, unique=False)[source]¶
A generator of (optionally unique) (predicate, object) tuples for the given subject
- predicates(subject=None, object=None, unique=False)[source]¶
A generator of (optionally unique) predicates with the given subject and object
- query(query_object, processor='sparql', result='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]¶
Query this graph.
A type of ‘prepared queries’ can be realised by providing initial variable bindings with initBindings
Initial namespaces are used to resolve prefixes used in the query, if none are given, the namespaces from the graph’s namespace manager are used.
Caution
This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in
SERVICE
directives.When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- remove(triple)[source]¶
Remove a triple from the graph
If the triple does not provide a context attribute, removes the triple from all contexts.
- 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
- serialize(destination=None, format='turtle', base=None, encoding=None, **args)[source]¶
Serialize the graph.
- Parameters:
destination (
Union
[str
,PurePath
,IO
[bytes
],None
]) – The destination to serialize the graph to. This can be a path as astr
orPurePath
object, or it can be aIO[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 aSerializer
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.args (
Any
) – Additional arguments to pass to theSerializer
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
ifdestination
is None andencoding
is not None.- Return type:
str
ifdestination
is None andencoding
is None.- Returns:
self
(i.e. theGraph
instance) ifdestination
is not None.- Return type:
Graph
ifdestination
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).
- subject_objects(predicate=None, unique=False)[source]¶
A generator of (optionally unique) (subject, object) tuples for the given predicate
- subject_predicates(object=None, unique=False)[source]¶
A generator of (optionally unique) (subject, predicate) tuples for the given object
- subjects(predicate=None, object=None, unique=False)[source]¶
A generator of (optionally unique) subjects with the given predicate and object
- 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')]
- transitive_objects(subject, predicate, remember=None)[source]¶
Transitively generate objects for the
predicate
relationshipGenerated objects belong to the depth first transitive closure of the
predicate
relationship starting atsubject
.
- transitive_subjects(predicate, object, remember=None)[source]¶
Transitively generate subjects for the
predicate
relationshipGenerated subjects belong to the depth first transitive closure of the
predicate
relationship starting atobject
.
- triples(triple)[source]¶
Generator over the triple store
Returns triples that match the given triple pattern. If triple pattern does not provide a context, all contexts will be searched.
- update(update_object, processor='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)[source]¶
Update this graph with the given update query.
Caution
This method can access indirectly requested network endpoints, for example, query processing will attempt to access network endpoints specified in
SERVICE
directives.When processing untrusted or potentially malicious queries, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- value(subject=None, predicate=rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#value'), object=None, default=None, any=True)[source]¶
Get a value for a pair of two criteria
Exactly one of subject, predicate, object must be None. Useful if one knows that there may only be one value.
It is one of those situations that occur a lot, hence this ‘macro’ like utility
Parameters: subject, predicate, object – exactly one must be None default – value to be returned if no values found any – if True, return any value in the case there is more than one, else, raise UniquenessError
- exception rdflib.graph.ModificationException[source]¶
Bases:
Exception
- __module__ = 'rdflib.graph'¶
- __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.
- __module__ = 'rdflib.graph'¶
- 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.
- __module__ = 'rdflib.graph'¶
- add(triple)[source]¶
Add a triple or quad to the store.
if a triple is given it is added to the default context
- 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/”)
- 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:
- 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.
- 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.
Caution
This method can access directly or indirectly requested network or file resources, for example, when parsing JSON-LD documents with
@context
directives that point to a network location.When processing untrusted or potentially malicious documents, measures should be taken to restrict network and file access.
For information on available security measures, see the RDFLib Security Considerations documentation.
- 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
- triples(triple)[source]¶
Iterate over all the triples in the entire conjunctive graph
For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence.
- 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.
- __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]]'}})¶
- __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!
- __module__ = 'rdflib.graph'¶
- __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'¶
- class rdflib.parser.InputSource(system_id=None)[source]¶
Bases:
InputSource
TODO:
- __module__ = 'rdflib.parser'¶
- class rdflib.parser.Parser[source]¶
Bases:
object
- __module__ = 'rdflib.parser'¶
- __slots__ = ()¶
- parse(source, sink)[source]¶
- Parameters:
source (
InputSource
) –sink (
Graph
) –
- Return type:
- 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
- __module__ = 'rdflib.parser'¶
- 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
- __module__ = 'rdflib.parser'¶
- 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.
- __annotations__ = {'links': 'List[str]'}¶
- __module__ = 'rdflib.parser'¶
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
- __module__ = 'rdflib.paths'¶
- n3(namespace_manager=None)[source]¶
- Parameters:
namespace_manager (
Optional
[NamespaceManager
]) –- Return type:
- class rdflib.paths.InvPath(arg)[source]¶
Bases:
Path
- __module__ = 'rdflib.paths'¶
- n3(namespace_manager=None)[source]¶
- Parameters:
namespace_manager (
Optional
[NamespaceManager
]) –- Return type:
- class rdflib.paths.MulPath(path, mod)[source]¶
Bases:
Path
- __module__ = 'rdflib.paths'¶
- n3(namespace_manager=None)[source]¶
- Parameters:
namespace_manager (
Optional
[NamespaceManager
]) –- Return type:
- class rdflib.paths.NegatedPath(arg)[source]¶
Bases:
Path
- Parameters:
arg (
Union
[AlternativePath
,InvPath
,URIRef
]) –
- __module__ = 'rdflib.paths'¶
- n3(namespace_manager=None)[source]¶
- Parameters:
namespace_manager (
Optional
[NamespaceManager
]) –- Return type:
- class rdflib.paths.Path[source]¶
Bases:
object
- __annotations__ = {'__invert__': "Callable[['Path'], 'InvPath']", '__mul__': "Callable[['Path', str], 'MulPath']", '__neg__': "Callable[['Path'], 'NegatedPath']", '__or__': "Callable[['Path', Union['URIRef', 'Path']], 'AlternativePath']", '__truediv__': "Callable[['Path', Union['URIRef', 'Path']], 'SequencePath']"}¶
- __dict__ = mappingproxy({'__module__': 'rdflib.paths', '__annotations__': {'__or__': "Callable[['Path', Union['URIRef', 'Path']], 'AlternativePath']", '__invert__': "Callable[['Path'], 'InvPath']", '__neg__': "Callable[['Path'], 'NegatedPath']", '__truediv__': "Callable[['Path', Union['URIRef', 'Path']], 'SequencePath']", '__mul__': "Callable[['Path', str], 'MulPath']"}, 'eval': <function Path.eval>, '__hash__': <function Path.__hash__>, '__eq__': <function Path.__eq__>, '__lt__': <function Path.__lt__>, '__dict__': <attribute '__dict__' of 'Path' objects>, '__weakref__': <attribute '__weakref__' of 'Path' objects>, '__doc__': None, '__gt__': <function _gt_from_lt>, '__le__': <function _le_from_lt>, '__ge__': <function _ge_from_lt>, '__invert__': <function inv_path>, '__neg__': <function neg_path>, '__mul__': <function mul_path>, '__or__': <function path_alternative>, '__truediv__': <function path_sequence>})¶
- __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).
- __le__(other, NotImplemented=NotImplemented)¶
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
- __module__ = 'rdflib.paths'¶
- __mul__(mul)¶
cardinality path
- __neg__()¶
negated path
- Parameters:
p (
Union
[URIRef
,AlternativePath
,InvPath
]) –- Return type:
- __or__(other)¶
alternative path
- __truediv__(other)¶
sequence path
- __weakref__¶
list of weak references to the object (if defined)
- 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
- __module__ = 'rdflib.paths'¶
- n3(namespace_manager=None)[source]¶
- Parameters:
namespace_manager (
Optional
[NamespaceManager
]) –- Return type:
- rdflib.paths.neg_path(p)[source]¶
negated path
- Parameters:
p (
Union
[URIRef
,AlternativePath
,InvPath
]) –- Return type:
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]¶
-
- __module__ = 'rdflib.plugin'¶
- __orig_bases__ = (rdflib.plugin.Plugin[~PluginT],)¶
- __parameters__ = (~PluginT,)¶
- class rdflib.plugin.Plugin(name, kind, module_path, class_name)[source]¶
-
- __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]]'}})¶
- __module__ = 'rdflib.plugin'¶
- __orig_bases__ = (typing.Generic[~PluginT],)¶
- __parameters__ = (~PluginT,)¶
- __weakref__¶
list of weak references to the object (if defined)
- 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.
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__': {}})¶
- __module__ = 'rdflib.query'¶
- __weakref__¶
list of weak references to the object (if defined)
- 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__': {}})¶
- __module__ = 'rdflib.query'¶
- __weakref__¶
list of weak references to the object (if defined)
- 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
) –
- __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']"}})¶
- __hash__ = None¶
- __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
- serialize(destination=None, encoding='utf-8', format='xml', **args)[source]¶
Serialize the query result.
The
format
argument determines the Serializer class to use.csv:
CSVResultSerializer
json:
JSONResultSerializer
txt:
TXTResultSerializer
xml:
XMLResultSerializer
- 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__': {}})¶
- __module__ = 'rdflib.query'¶
- __weakref__¶
list of weak references to the object (if defined)
- 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__': ()})¶
- __module__ = 'rdflib.query'¶
- static __new__(cls, values, labels)[source]¶
- Parameters:
values (
Mapping
[Variable
,Identifier
]) –
- __orig_bases__ = (typing.Tuple[ForwardRef('Identifier'), ...],)¶
- __parameters__ = ()¶
- get(name, default=None)[source]¶
- Parameters:
name (
str
) –default (
Optional
[Identifier
]) –
- Return type:
- 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__': {}})¶
- __module__ = 'rdflib.query'¶
- __weakref__¶
list of weak references to the object (if defined)
- 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__': {}})¶
- __module__ = 'rdflib.query'¶
- __weakref__¶
list of weak references to the object (if defined)
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