# rdflib Package

## `rdflib` Package

A pure Python package providing the core RDF constructs.

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

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

A tiny example:

    >>> from rdflib import Graph, URIRef, Literal

    >>> g = Graph()
    >>> result = g.parse("http://www.w3.org/2000/10/swap/test/meet/blue.rdf")

    >>> print("graph has %s statements." % len(g))
    graph has 4 statements.
    >>>
    >>> for s, p, o in g:
    ...     if (s, p, o) not in g:
    ...         raise Exception("It better be!")

    >>> s = g.serialize(format='nt')
    >>>
    >>> sorted(g) == [
    ...  (URIRef(u'http://meetings.example.com/cal#m1'),
    ...   URIRef(u'http://www.example.org/meeting_organization#homePage'),
    ...   URIRef(u'http://meetings.example.com/m1/hp')),
    ...  (URIRef(u'http://www.example.org/people#fred'),
    ...   URIRef(u'http://www.example.org/meeting_organization#attending'),
    ...   URIRef(u'http://meetings.example.com/cal#m1')),
    ...  (URIRef(u'http://www.example.org/people#fred'),
    ...   URIRef(u'http://www.example.org/personal_details#GivenName'),
    ...   Literal(u'Fred')),
    ...  (URIRef(u'http://www.example.org/people#fred'),
    ...   URIRef(u'http://www.example.org/personal_details#hasEmail'),
    ...   URIRef(u'mailto:fred@example.com'))
    ... ]
    True

`rdflib.__init__.``NORMALIZE_LITERALS` = True

  If True - Literals lexical forms are normalized when created. I.e. the lexical forms is parsed according to data-type, then the stored lexical form is the re-serialized value that was parsed.

  Illegal values for a datatype are simply kept. The normalized keyword for Literal.__new__ can override this.

  For example:

      >>> from rdflib import Literal,XSD
      >>> Literal("01", datatype=XSD.int)
      rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))

  This flag may be changed at any time, but will only affect literals created after that time, previously created literals will remain (un)normalized.

`rdflib.__init__.``DAWG_LITERAL_COLLATION` = False

  DAWG_LITERAL_COLLATION determines how literals are ordered or compared to each other.

  In SPARQL, applying the >,<,>=,<= operators to literals of incompatible data-types is an error, i.e:

  Literal(2)>Literal(‘cake’) is neither true nor false, but an error.

  This is a problem in PY3, where lists of Literals of incompatible types can no longer be sorted.

  Setting this flag to True gives you strict DAWG/SPARQL compliance, setting it to False will order Literals with incompatible datatypes by datatype URI

  In particular, this determines how the rich comparison operators for Literal work, eq, __neq__, __lt__, etc.

## `collection` Module

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

  Bases: `object`

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

      >>> from rdflib.graph import Graph
      >>> from pprint import pprint
      >>> listName = BNode()
      >>> g = Graph('IOMemory')
      >>> listItem1 = BNode()
      >>> listItem2 = BNode()
      >>> g.add((listName, RDF.first, Literal(1)))
      >>> g.add((listName, RDF.rest, listItem1))
      >>> g.add((listItem1, RDF.first, Literal(2)))
      >>> g.add((listItem1, RDF.rest, listItem2))
      >>> g.add((listItem2, RDF.rest, RDF.nil))
      >>> g.add((listItem2, RDF.first, Literal(3)))
      >>> c = Collection(g,listName)
      >>> pprint([term.n3() for term in c])
      ['"1"^^<http://www.w3.org/2001/XMLSchema#integer>',
       '"2"^^<http://www.w3.org/2001/XMLSchema#integer>',
       '"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)

        >>> 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))
        >>> g.add((a, RDF.rest, b))
        >>> g.add((b, RDF.first, RDFS.label))
        >>> g.add((b, RDF.rest, c))
        >>> g.add((c, RDF.first, RDFS.comment))
        >>> g.add((c, RDF.rest, RDF.nil))
        >>> 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

  `__getitem__`(key)

    TODO

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

    Initialize self. See help(type(self)) for accurate signature.

  `__iter__`()

    Iterator over items in Collections

  `__len__`()

    length of items in collection.

  `__module__` = 'rdflib.collection'
  `__setitem__`(key, value)

    TODO

  `append`(item)

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

  `clear`()
  `index`(item)

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

  `n3`()

        >>> from rdflib.graph import Graph
        >>> listName = BNode()
        >>> g = Graph('IOMemory')
        >>> listItem1 = BNode()
        >>> listItem2 = BNode()
        >>> g.add((listName, RDF.first, Literal(1)))
        >>> g.add((listName, RDF.rest, listItem1))
        >>> g.add((listItem1, RDF.first, Literal(2)))
        >>> g.add((listItem1, RDF.rest, listItem2))
        >>> g.add((listItem2, RDF.rest, RDF.nil))
        >>> g.add((listItem2, RDF.first, Literal(3)))
        >>> c = Collection(g, listName)
        >>> print(c.n3()) #doctest: +NORMALIZE_WHITESPACE
        ( "1"^^<http://www.w3.org/2001/XMLSchema#integer>
          "2"^^<http://www.w3.org/2001/XMLSchema#integer>
          "3"^^<http://www.w3.org/2001/XMLSchema#integer> )

## `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)

  Bases: `rdflib.graph.ConjunctiveGraph`

  An implementation of the RGDA1 graph digest algorithm.

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

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

  `__eq__`(other)

    Graph isomorphism testing.

  `__hash__` = None
  `__init__`(**kwargs)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.compare'
  `__ne__`(other)

    Negative graph isomorphism testing.

  `graph_digest`(stats=None)

    Synonym for IsomorphicGraph.internal_hash.

  `internal_hash`(stats=None)

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

`rdflib.compare.``to_isomorphic`(graph)

`rdflib.compare.``isomorphic`(graph1, graph2)

  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.``to_canonical_graph`(g1)

  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.compare.``graph_diff`(g1, g2)

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

`rdflib.compare.``similar`(g1, g2)

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

## `compat` Module

`rdflib.compat.``numeric_greater`(a, b)

## `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)

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.``Event`(**kw)

  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.

  `__init__`(**kw)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.events'
  `__repr__`()

    Return repr(self).

class `rdflib.events.``Dispatcher`

  Bases: `object`

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

  `__module__` = 'rdflib.events'
  `dispatch`(event)

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

  `get_map`()
  `set_map`(amap)
  `subscribe`(event_type, handler)

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

## `exceptions` Module

TODO:

exception `rdflib.exceptions.``Error`(msg=None)

  Bases: `Exception`

  Base class for rdflib exceptions.

  `__init__`(msg=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'
  `__weakref__`

    list of weak references to the object (if defined)

exception `rdflib.exceptions.``TypeCheckError`(node)

  Bases: `rdflib.exceptions.Error`

  Parts of assertions are subject to type checks.

  `__init__`(node)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'

exception `rdflib.exceptions.``SubjectTypeError`(node)

  Bases: `rdflib.exceptions.TypeCheckError`

  Subject of an assertion must be an instance of URIRef.

  `__init__`(node)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'

exception `rdflib.exceptions.``PredicateTypeError`(node)

  Bases: `rdflib.exceptions.TypeCheckError`

  Predicate of an assertion must be an instance of URIRef.

  `__init__`(node)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'

exception `rdflib.exceptions.``ObjectTypeError`(node)

  Bases: `rdflib.exceptions.TypeCheckError`

  Object of an assertion must be an instance of URIRef, Literal, or BNode.

  `__init__`(node)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'

exception `rdflib.exceptions.``ContextTypeError`(node)

  Bases: `rdflib.exceptions.TypeCheckError`

  Context of an assertion must be an instance of URIRef.

  `__init__`(node)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'

exception `rdflib.exceptions.``ParserError`(msg)

  Bases: `rdflib.exceptions.Error`

  RDF Parser error.

  `__init__`(msg)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.exceptions'
  `__str__`()

    Return str(self).

## `graph` Module

RDFLib defines the following kinds of Graphs:

- `Graph`
- `QuotedGraph`
- `ConjunctiveGraph`
- `Dataset`

### 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 (IOMemory) and default identifier (a BNode):

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

Instantiating Graphs with a IOMemory store and an identifier - <http://rdflib.net>:

    >>> g = Graph('IOMemory', URIRef("http://rdflib.net"))
    >>> g.identifier
    rdflib.term.URIRef('http://rdflib.net')
    >>> str(g) # doctest: +NORMALIZE_WHITESPACE
    "<http://rdflib.net> a rdfg:Graph;rdflib:storage
     [a rdflib:Store;rdfs:label 'IOMemory']."

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 'IOMemory']]."

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))
    >>> g.add((statementId, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g.add((statementId, RDF.predicate, RDFS.label))
    >>> g.add((statementId, RDF.object, Literal("Conjunctive 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))
    >>> 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, RDFS.label, Literal('foo')])
    >>> g1.add([u, RDFS.label, Literal('bar')])
    >>> g2.add([u, RDFS.label, Literal('foo')])
    >>> g2.add([u, RDFS.label, Literal('bing')])
    >>> 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('IOMemory', Store)()
    >>> g1 = Graph(store)
    >>> g2 = Graph(store)
    >>> g3 = Graph(store)
    >>> stmt1 = BNode()
    >>> stmt2 = BNode()
    >>> stmt3 = BNode()
    >>> g1.add((stmt1, RDF.type, RDF.Statement))
    >>> g1.add((stmt1, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g1.add((stmt1, RDF.predicate, RDFS.label))
    >>> g1.add((stmt1, RDF.object, Literal("Conjunctive Graph")))
    >>> g2.add((stmt2, RDF.type, RDF.Statement))
    >>> g2.add((stmt2, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g2.add((stmt2, RDF.predicate, RDF.type))
    >>> g2.add((stmt2, RDF.object, RDFS.Class))
    >>> g3.add((stmt3, RDF.type, RDF.Statement))
    >>> g3.add((stmt3, RDF.subject,
    ...     URIRef('http://rdflib.net/store/ConjunctiveGraph')))
    >>> g3.add((stmt3, RDF.predicate, RDFS.comment))
    >>> g3.add((stmt3, RDF.object, Literal(
    ...     "The top-level aggregate graph - The sum " +
    ...     "of all named graphs within a Store")))
    >>> 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 <http://rdflib.net/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('http://rdflib.net/')
    >>> RDFLib.ConjunctiveGraph
    rdflib.term.URIRef('http://rdflib.net/ConjunctiveGraph')
    >>> RDFLib['Graph']
    rdflib.term.URIRef('http://rdflib.net/Graph')

class `rdflib.graph.``Graph`(store='default', identifier=None, namespace_manager=None)

  Bases: `rdflib.term.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.

  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/

  `__add__`(other)

    Set-theoretic union BNode IDs are not changed.

  `__and__`(other)

    Set-theoretic intersection. BNode IDs are not changed.

  `__cmp__`(other)
  `__contains__`(triple)

    Support for ‘triple in graph’ syntax

  `__eq__`(other)

    Return self==value.

  `__ge__`(other)

    Return self>=value.

  `__getitem__`(item)

    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'), rdflib.RDFS.label, rdflib.Literal('Bob')))

        >>> 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[:rdflib.RDFS.label]) # all label triples
        [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]

        >>> list(g[::rdflib.Literal('Bob')]) # all triples with bob as object
        [(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]

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

    Name of all Bobs friends:

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

    Some label for Bob:

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

    All friends and friends of friends of Bob

    g[bob : FOAF.knows * ‘+’]

    etc.

    New in version 4.0.

  `__gt__`(other)

    Return self>value.

  `__hash__`()

    Return hash(self).

  `__iadd__`(other)

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

  `__init__`(store='default', identifier=None, namespace_manager=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__isub__`(other)

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

  `__iter__`()

    Iterates over all triples in the store

  `__le__`(other)

    Return self<=value.

  `__len__`()

    Returns the number of triples in the graph

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

  `__lt__`(other)

    Return self<value.

  `__module__` = 'rdflib.graph'
  `__mul__`(other)

    Set-theoretic intersection. BNode IDs are not changed.

  `__or__`(other)

    Set-theoretic union BNode IDs are not changed.

  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `__str__`()

    Return str(self).

  `__sub__`(other)

    Set-theoretic difference. BNode IDs are not changed.

  `__xor__`(other)

    Set-theoretic XOR. BNode IDs are not changed.

  `absolutize`(uri, defrag=1)

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

  `add`(xxx_todo_changeme)

    Add a triple with self as context

  `addN`(quads)

    Add a sequence of triple with context

  `all_nodes`()
  `bind`(prefix, namespace, override=True)

    Bind prefix to namespace

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

    for example: graph.bind(‘foaf’, ‘http://xmlns.com/foaf/0.1/’)

  `close`(commit_pending_transaction=False)

    Close the graph store

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

  `collection`(identifier)

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

  `comment`(subject, default='')

    Query for the RDFS.comment of the subject

    Return default if no comment exists

  `commit`()

    Commits active transactions

  `compute_qname`(uri, generate=True)
  `connected`()

    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.

  `de_skolemize`(new_graph=None, uriref=None)
  `destroy`(configuration)

    Destroy the store identified by configuration if supported

  `identifier`
  `isomorphic`(other)

    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)

    Generator over all items in the resource specified by list

    list is an RDF collection.

  `label`(subject, default='')

    Query for the RDFS.label of the subject

    Return default if no label exists or any label if multiple exist.

  `load`(source, publicID=None, format='xml')
  `md5_term_hash`()
  `n3`()

    return an n3 identifier for the Graph

  `namespace_manager`

    this graph’s namespace-manager

  `namespaces`()

    Generator over all the prefix, namespace tuples

  `objects`(subject=None, predicate=None)

    A generator of objects with the given subject and predicate

  `open`(configuration, create=False)

    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)

    Parse source adding the resulting triples to the Graph.

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

    Parameters:

    - source: An InputSource, file-like object, or string. In the case of a string the string is the location of the source.
    - location: A string indicating the relative or absolute URL of the source. Graph’s absolutize method is used if a relative location is specified.
    - file: A file-like object.
    - data: A string containing the data to be parsed.
    - format: Used if format can not be determined from source. Defaults to rdf/xml. Format support can be extended with plugins, but ‘xml’, ‘n3’, ‘nt’, ‘trix’, ‘rdfa’ 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 tempfile
        >>> fd, file_name = tempfile.mkstemp()
        >>> f = os.fdopen(fd, 'w')
        >>> dummy = f.write(my_data)  # Returns num bytes written on py3
        >>> 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)

  `predicate_objects`(subject=None)

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

  `predicates`(subject=None, object=None)

    A generator of predicates with the given subject and object

  `preferredLabel`(subject, lang=None, default=None, labelProperties=(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label')))

    Find the preferred label for subject.

    By default prefers skos:prefLabels over rdfs:labels. In case at least one prefLabel is found returns those, else returns labels. In case a language string (e.g., ‘en’, ‘de’ or even ‘’ for no lang-tagged literals) is given, only such labels will be considered.

    Return a list of (labelProp, label) pairs, where labelProp is either skos:prefLabel or rdfs:label.

        >>> from rdflib import ConjunctiveGraph, URIRef, RDFS, Literal
        >>> from rdflib.namespace import SKOS
        >>> from pprint import pprint
        >>> g = ConjunctiveGraph()
        >>> u = URIRef('http://example.com/foo')
        >>> g.add([u, RDFS.label, Literal('foo')])
        >>> g.add([u, RDFS.label, Literal('bar')])
        >>> pprint(sorted(g.preferredLabel(u)))
        [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),
          rdflib.term.Literal('bar')),
         (rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'),
          rdflib.term.Literal('foo'))]
        >>> g.add([u, SKOS.prefLabel, Literal('bla')])
        >>> pprint(g.preferredLabel(u))
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla'))]
        >>> g.add([u, SKOS.prefLabel, Literal('blubb', lang='en')])
        >>> sorted(g.preferredLabel(u)) #doctest: +NORMALIZE_WHITESPACE
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla')),
          (rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('blubb', lang='en'))]
        >>> g.preferredLabel(u, lang='') #doctest: +NORMALIZE_WHITESPACE
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('bla'))]
        >>> pprint(g.preferredLabel(u, lang='en'))
        [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'),
          rdflib.term.Literal('blubb', lang='en'))]

  `qname`(uri)
  `query`(query_object, processor='sparql', result='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)

    Query this graph.

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

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

    Returntype: | rdflib.query.QueryResult

  `remove`(xxx_todo_changeme1)

    Remove a triple from the graph

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

  `resource`(identifier)

    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

  `rollback`()

    Rollback active transactions

  `seq`(subject)

    Check if subject is an rdf:Seq

    If yes, it returns a Seq class instance, None otherwise.

  `serialize`(destination=None, format='xml', base=None, encoding=None, **args)

    Serialize the Graph to destination

    If destination is None serialize method returns the serialization as a string. Format defaults to xml (AKA rdf/xml).

    Format support can be extended with plugins, but ‘xml’, ‘n3’, ‘turtle’, ‘nt’, ‘pretty-xml’, ‘trix’, ‘trig’ and ‘nquads’ are built in.

  `set`(triple)

    Convenience method to update the value of object

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

  `skolemize`(new_graph=None, bnode=None)
  `store`
  `subject_objects`(predicate=None)

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

  `subject_predicates`(object=None)

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

  `subjects`(predicate=None, object=None)

    A generator of subjects with the given predicate and object

  `toPython`()
  `transitiveClosure`(func, arg, seen=None)

    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))
        >>> g.add((a,RDF.rest,b))
        >>> g.add((b,RDF.first,RDFS.label))
        >>> g.add((b,RDF.rest,c))
        >>> g.add((c,RDF.first,RDFS.comment))
        >>> g.add((c,RDF.rest,RDF.nil))
        >>> 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)] # doctest: +NORMALIZE_WHITESPACE
        [rdflib.term.BNode('baz'),
         rdflib.term.BNode('bar'),
         rdflib.term.BNode('foo')]

        >>> [rt for rt in g.transitiveClosure(
        ...     reverseList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE
        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, property, remember=None)

    Transitively generate objects for the `property` relationship

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

  `transitive_subjects`(predicate, object, remember=None)

    Transitively generate objects for the `property` relationship

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

  `triples`(xxx_todo_changeme2)

    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.

  `triples_choices`(xxx_todo_changeme3, context=None)
  `update`(update_object, processor='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs)

    Update this graph with the given update query.

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

    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

class `rdflib.graph.``ConjunctiveGraph`(store='default', identifier=None)

  Bases: `rdflib.graph.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.

  `__contains__`(triple_or_quad)

    Support for ‘triple/quad in graph’ syntax

  `__init__`(store='default', identifier=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__len__`()

    Number of triples in the entire conjunctive graph

  `__module__` = 'rdflib.graph'
  `__reduce__`()

    Helper for pickle.

  `__str__`()

    Return str(self).

  `add`(triple_or_quad)

    Add a triple or quad to the store.

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

  `addN`(quads)

    Add a sequence of triples with context

  `context_id`(uri, context_id=None)

    URI#context

  `contexts`(triple=None)

    Iterate over all contexts in the graph

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

  `get_context`(identifier, quoted=False)

    Return a context graph for the given identifier

    identifier must be a URIRef or BNode.

  `parse`(source=None, publicID=None, format='xml', location=None, file=None, data=None, **args)

    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.

  `quads`(triple_or_quad=None)

    Iterate over all the quads in the entire conjunctive graph

  `remove`(triple_or_quad)

    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

  `remove_context`(context)

    Removes the given context from the graph

  `triples`(triple_or_quad, context=None)

    Iterate over all the triples in the entire conjunctive graph

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

  `triples_choices`(xxx_todo_changeme4, context=None)

    Iterate over all the triples in the entire conjunctive graph

class `rdflib.graph.``QuotedGraph`(store, identifier)

  Bases: `rdflib.graph.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.

  `__init__`(store, identifier)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.graph'
  `__reduce__`()

    Helper for pickle.

  `__str__`()

    Return str(self).

  `add`(xxx_todo_changeme5)

    Add a triple with self as context

  `addN`(quads)

    Add a sequence of triple with context

  `n3`()

    Return an n3 identifier for the Graph

class `rdflib.graph.``Seq`(graph, subject)

  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.

  `__getitem__`(index)

    Item given by index from the Seq

  `__init__`(graph, subject)

    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!
  `__iter__`()

    Generator over the items in the Seq

  `__len__`()

    Length of the Seq

  `__module__` = 'rdflib.graph'
  `toPython`()

exception `rdflib.graph.``ModificationException`

  Bases: `Exception`

  `__init__`()

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.graph'
  `__str__`()

    Return str(self).

class `rdflib.graph.``Dataset`(store='default', default_union=False)

  Bases: `rdflib.graph.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')))
      >>>
      >>> # 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')) )
      >>> # 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) )
      >>>
      >>> # querying triples return them all regardless of the graph
      >>> for t in ds.triples((None,None,None)):  # doctest: +SKIP
      ...     print(t)  # doctest: +NORMALIZE_WHITESPACE
      (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
      >>> # or restricted to a graph
      >>> for q in ds.quads((None, None, None, None)):  # doctest: +SKIP
      ...     print(q)  # doctest: +NORMALIZE_WHITESPACE
      (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'))
      >>>
      >>> for q in ds.quads((None,None,None,g)):  # doctest: +SKIP
      ...     print(q)  # doctest: +NORMALIZE_WHITESPACE
      (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():  # doctest: +SKIP
      ...     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():  # doctest: +SKIP
      ...     print(c)  # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
      DEFAULT
      http://rdlib.net/.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):  # doctest: +SKIP
      ...     print(c)  # doctest: +NORMALIZE_WHITESPACE
      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.

  `__init__`(store='default', default_union=False)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.graph'
  `__str__`()

    Return str(self).

  `add_graph`(g)

    alias of graph for consistency

  `contexts`(triple=None)

    Iterate over all contexts in the graph

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

  `graph`(identifier=None)
  `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='xml', location=None, file=None, data=None, **args)

    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.

  `quads`(quad)

    Iterate over all the quads in the entire conjunctive graph

  `remove_graph`(g)

exception `rdflib.graph.``UnSupportedAggregateOperation`

  Bases: `Exception`

  `__init__`()

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.graph'
  `__str__`()

    Return str(self).

class `rdflib.graph.``ReadOnlyGraphAggregate`(graphs, store='default')

  Bases: `rdflib.graph.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.

  `__cmp__`(other)
  `__contains__`(triple_or_quad)

    Support for ‘triple/quad in graph’ syntax

  `__hash__`()

    Return hash(self).

  `__iadd__`(other)

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

  `__init__`(graphs, store='default')

    Initialize self. See help(type(self)) for accurate signature.

  `__isub__`(other)

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

  `__len__`()

    Number of triples in the entire conjunctive graph

  `__module__` = 'rdflib.graph'
  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `absolutize`(uri, defrag=1)

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

  `add`(xxx_todo_changeme6)

    Add a triple or quad to the store.

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

  `addN`(quads)

    Add a sequence of triples with context

  `bind`(prefix, namespace, override=True)

    Bind prefix to namespace

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

    for example: graph.bind(‘foaf’, ‘http://xmlns.com/foaf/0.1/’)

  `close`()

    Close the graph store

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

  `commit`()

    Commits active transactions

  `compute_qname`(uri, generate=True)
  `destroy`(configuration)

    Destroy the store identified by configuration if supported

  `n3`()

    return an n3 identifier for the Graph

  `namespaces`()

    Generator over all the prefix, namespace tuples

  `open`(configuration, create=False)

    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='xml', **args)

    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.

  `qname`(uri)
  `quads`(xxx_todo_changeme9)

    Iterate over all the quads in the entire aggregate graph

  `remove`(xxx_todo_changeme7)

    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

  `rollback`()

    Rollback active transactions

  `triples`(xxx_todo_changeme8)

    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.

  `triples_choices`(xxx_todo_changeme10, context=None)

    Iterate over all the triples in the entire conjunctive graph

## `namespace` Module

### Namespace Utilities

RDFLib provides mechanisms for managing Namespaces.

In particular, there is a `Namespace` class that takes as its argument the base URI of the namespace.

    >>> from rdflib.namespace import Namespace
    >>> owl = Namespace('http://www.w3.org/2002/07/owl#')

Fully qualified URIs in the namespace can be constructed either by attribute or by dictionary access on Namespace instances:

    >>> owl.seeAlso
    rdflib.term.URIRef('http://www.w3.org/2002/07/owl#seeAlso')
    >>> owl['seeAlso']
    rdflib.term.URIRef('http://www.w3.org/2002/07/owl#seeAlso')

#### Automatic handling of unknown predicates

As a programming convenience, a namespace binding is automatically created when `rdflib.term.URIRef` predicates are added to the graph.

#### Importable namespaces

The following namespaces are available by directly importing from rdflib:

- RDF
- RDFS
- OWL
- XSD
- FOAF
- SKOS
- DOAP
- DC
- DCTERMS
- VOID

    >>> from rdflib import OWL
    >>> OWL.seeAlso
    rdflib.term.URIRef('http://www.w3.org/2002/07/owl#seeAlso')

`rdflib.namespace.``is_ncname`(name)

`rdflib.namespace.``split_uri`(uri)

class `rdflib.namespace.``Namespace`

  Bases: `str`

  Utility class for quickly generating URIRefs with a common prefix

      >>> from rdflib import Namespace
      >>> n = Namespace("http://example.org/")
      >>> n.Person # as attribute
      rdflib.term.URIRef('http://example.org/Person')
      >>> n['first-name'] # as item - for things that are not valid python identifiers
      rdflib.term.URIRef('http://example.org/first-name')

  `__getattr__`(name)
  `__getitem__`(key, default=None)

    Return self[key].

  `__module__` = 'rdflib.namespace'
  static `__new__`(cls, value)

    Create and return a new object. See help(type) for accurate signature.

  `__repr__`()

    Return repr(self).

  `term`(name)
  `title`

    Return a version of the string where each word is titlecased.

    More specifically, words start with uppercased characters and all remaining cased characters have lower case.

class `rdflib.namespace.``ClosedNamespace`(uri, terms)

  Bases: `object`

  A namespace with a closed list of members

  Trying to create terms not listen is an error

  `__getattr__`(name)
  `__getitem__`(key, default=None)
  `__init__`(uri, terms)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.namespace'
  `__repr__`()

    Return repr(self).

  `__str__`()

    Return str(self).

  `term`(name)

class `rdflib.namespace.``NamespaceManager`(graph)

  Bases: `object`

  Class for managing prefix => namespace mappings

  Sample usage from FuXi …

      ruleStore = N3RuleStore(additionalBuiltins=additionalBuiltins)
      nsMgr = NamespaceManager(Graph(ruleStore))
      ruleGraph = Graph(ruleStore,namespace_manager=nsMgr)

  and …

      >>> import rdflib
      >>> from rdflib import Graph
      >>> from rdflib.namespace import Namespace, NamespaceManager
      >>> exNs = Namespace('http://example.com/')
      >>> namespace_manager = NamespaceManager(Graph())
      >>> namespace_manager.bind('ex', exNs, override=False)
      >>> g = Graph()
      >>> g.namespace_manager = namespace_manager
      >>> all_ns = [n for n in g.namespace_manager.namespaces()]
      >>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns
      >>>

  `__init__`(graph)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.namespace'
  `absolutize`(uri, defrag=1)
  `bind`(prefix, namespace, override=True, replace=False)

    bind a given namespace to the prefix

    if override, rebind, even if the given namespace is already bound to another prefix.

    if replace, replace any existing prefix with the new namespace

  `compute_qname`(uri, generate=True)
  `namespaces`()
  `normalizeUri`(rdfTerm)

    Takes an RDF Term and ‘normalizes’ it into a QName (using the registered prefix) or (unlike compute_qname) the Notation 3 form for URIs: <…URI…>

  `qname`(uri)
  `reset`()
  `store`

## `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.``Parser`

  Bases: `object`

  `__init__`()

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.parser'
  `parse`(source, sink)

class `rdflib.parser.``InputSource`(system_id=None)

  Bases: `xml.sax.xmlreader.InputSource`, `object`

  TODO:

  `__init__`(system_id=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.parser'
  `close`()

class `rdflib.parser.``StringInputSource`(value, system_id=None)

  Bases: `rdflib.parser.InputSource`

  TODO:

  `__init__`(value, system_id=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.parser'

class `rdflib.parser.``URLInputSource`(system_id=None, format=None)

  Bases: `rdflib.parser.InputSource`

  TODO:

  `__init__`(system_id=None, format=None)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.parser'
  `__repr__`()

    Return repr(self).

class `rdflib.parser.``FileInputSource`(file)

  Bases: `rdflib.parser.InputSource`

  `__init__`(file)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.parser'
  `__repr__`()

    Return repr(self).

## `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 be the SPARQL engine, but they 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

    >>> foaf=Namespace('http://xmlns.com/foaf/0.1/')

    >>> ~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.firstName
    Path(http://xmlns.com/foaf/0.1/name | http://xmlns.com/foaf/0.1/firstName)

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') # doctest: +ELLIPSIS

    >>> 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)) # doctest: +NORMALIZE_WHITESPACE
    [rdflib.term.URIRef('ex:j'), rdflib.term.URIRef('ex:g'),
        rdflib.term.URIRef('ex:f')]

A more complete set of tests:

    >>> list(evalPath(g, (None, e.p1/e.p2, None)))==[(e.a, e.e)]
    True
    >>> list(evalPath(g, (e.a, e.p1|e.p2, None)))==[(e.a,e.c), (e.a,e.f)]
    True
    >>> list(evalPath(g, (e.c, ~e.p1, None))) == [ (e.c, e.a) ]
    True
    >>> list(evalPath(g, (e.a, e.p1*ZeroOrOne, None))) == [(e.a, e.a), (e.a, e.c)]
    True
    >>> list(evalPath(g, (e.c, e.p3*OneOrMore, None))) == [
    ...     (e.c, e.g), (e.c, e.h), (e.c, e.a)]
    True
    >>> list(evalPath(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(evalPath(g, (e.a, -e.p1, None))) == [(e.a, e.f)]
    True
    >>> list(evalPath(g, (e.a, -(e.p1|e.p2), None))) == []
    True
    >>> list(evalPath(g, (e.g, -~e.p2, None))) == [(e.g, e.j)]
    True
    >>> list(evalPath(g, (e.e, ~(e.p1/e.p2), None))) == [(e.e, e.a)]
    True
    >>> list(evalPath(g, (e.a, e.p1/e.p3/e.p3, None))) == [(e.a, e.h)]
    True

    >>> list(evalPath(g, (e.q, e.px*OneOrMore, None)))
    [(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))]

    >>> list(evalPath(g, (None, e.p1|e.p2, e.c)))
    [(rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))]

    >>> list(evalPath(g, (None, ~e.p1, e.a))) == [ (e.c, e.a) ]
    True
    >>> list(evalPath(g, (None, e.p1*ZeroOrOne, e.c))) # doctest: +NORMALIZE_WHITESPACE
    [(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:c')),
     (rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))]

    >>> list(evalPath(g, (None, e.p3*OneOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE
    [(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(evalPath(g, (None, e.p3*ZeroOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE
    [(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(evalPath(g, (None, -e.p1, e.f))) == [(e.a, e.f)]
    True
    >>> list(evalPath(g, (None, -(e.p1|e.p2), e.c))) == []
    True
    >>> list(evalPath(g, (None, -~e.p2, e.j))) == [(e.g, e.j)]
    True
    >>> list(evalPath(g, (None, ~(e.p1/e.p2), e.a))) == [(e.e, e.a)]
    True
    >>> list(evalPath(g, (None, e.p1/e.p3/e.p3, e.h))) == [(e.a, e.h)]
    True

    >>> list(evalPath(g, (e.q, e.px*OneOrMore, None)))
    [(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))]

    >>> list(evalPath(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(evalPath(g, (None, e.p3*OneOrMore, None)))) #doctest: +NORMALIZE_WHITESPACE
    [(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'))]

New in version 4.0.

class `rdflib.paths.``AlternativePath`(*args)

  Bases: `rdflib.paths.Path`

  `__init__`(*args)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.paths'
  `__repr__`()

    Return repr(self).

  `eval`(graph, subj=None, obj=None)
  `n3`()

class `rdflib.paths.``InvPath`(arg)

  Bases: `rdflib.paths.Path`

  `__init__`(arg)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.paths'
  `__repr__`()

    Return repr(self).

  `eval`(graph, subj=None, obj=None)
  `n3`()

class `rdflib.paths.``MulPath`(path, mod)

  Bases: `rdflib.paths.Path`

  `__init__`(path, mod)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.paths'
  `__repr__`()

    Return repr(self).

  `eval`(graph, subj=None, obj=None, first=True)
  `n3`()

class `rdflib.paths.``NegatedPath`(arg)

  Bases: `rdflib.paths.Path`

  `__init__`(arg)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.paths'
  `__repr__`()

    Return repr(self).

  `eval`(graph, subj=None, obj=None)
  `n3`()

class `rdflib.paths.``Path`

  Bases: `object`

  `__eq__`(other)

    Return self==value.

  `__ge__`(other)

    Return self>=value.

  `__gt__`(other)

    Return self>value.

  `__hash__`()

    Return hash(self).

  `__invert__`()

    inverse path

  `__le__`(other)

    Return self<=value.

  `__lt__`(other)

    Return self<value.

  `__module__` = 'rdflib.paths'
  `__mul__`(mul)

    cardinality path

  `__ne__`(other)

    Return self!=value.

  `__neg__`()

    negated path

  `__or__`(other)

    alternative path

  `__truediv__`(other)

    sequence path

  `eval`(graph, subj=None, obj=None)

class `rdflib.paths.``PathList`

  Bases: `list`

  `__module__` = 'rdflib.paths'

class `rdflib.paths.``SequencePath`(*args)

  Bases: `rdflib.paths.Path`

  `__init__`(*args)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.paths'
  `__repr__`()

    Return repr(self).

  `eval`(graph, subj=None, obj=None)
  `n3`()

`rdflib.paths.``evalPath`(graph, t)

`rdflib.paths.``inv_path`(p)

  inverse path

`rdflib.paths.``mul_path`(p, mul)

  cardinality path

`rdflib.paths.``neg_path`(p)

  negated path

`rdflib.paths.``path_alternative`(self, other)

  alternative path

`rdflib.paths.``path_sequence`(self, other)

  sequence path

## `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.nt:NTParser',
            ],
        'rdf.plugins.serializer': [
            'nt =     rdf.plugins.serializers.NTSerializer:NTSerializer',
            ],
        }

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

`rdflib.plugin.``register`(name, kind, module_path, class_name)

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

`rdflib.plugin.``get`(name, kind)

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

`rdflib.plugin.``plugins`(name=None, kind=None)

  A generator of the plugins.

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

exception `rdflib.plugin.``PluginException`(msg=None)

  Bases: `rdflib.exceptions.Error`

  `__module__` = 'rdflib.plugin'

class `rdflib.plugin.``Plugin`(name, kind, module_path, class_name)

  Bases: `object`

  `__init__`(name, kind, module_path, class_name)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.plugin'
  `getClass`()

class `rdflib.plugin.``PKGPlugin`(name, kind, ep)

  Bases: `rdflib.plugin.Plugin`

  `__init__`(name, kind, ep)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.plugin'
  `getClass`()

## `py3compat` Module

Utility functions and objects to ease Python 3 compatibility.

`rdflib.py3compat.``ascii`(stream)

`rdflib.py3compat.``b`(s)

`rdflib.py3compat.``bopen`(*args, **kwargs)

`rdflib.py3compat.``cast_bytes`(s, enc='utf-8')

`rdflib.py3compat.``decodeStringEscape`(s)

  s is byte-string - replace escapes in string

`rdflib.py3compat.``decodeUnicodeEscape`(s)

  > s is a unicode string replace

  and u00AC unicode escapes

`rdflib.py3compat.``format_doctest_out`(s)

  Python 2 version “%(u)s’abc’” –> “‘abc’” “%(b)s’abc’” –> “b’abc’” “55%(L)s” –> “55” “unicode(x)” –> “str(x)”

  Accepts a string or a function, so it can be used as a decorator.

`rdflib.py3compat.``sign`(n)

`rdflib.py3compat.``type_cmp`(a, b)

  Python 2 style comparison based on type

## `query` Module

class `rdflib.query.``ResultRow`

  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('urn:cake')
      >>> rr[1]
      Traceback (most recent call last):
          ...
      IndexError: tuple index out of range

      >>> rr.a
      rdflib.term.URIRef('urn:cake')
      >>> rr.b
      Traceback (most recent call last):
          ...
      AttributeError: b

      >>> rr['a']
      rdflib.term.URIRef('urn:cake')
      >>> rr['b']
      Traceback (most recent call last):
          ...
      KeyError: 'b'

      >>> rr[Variable('a')]
      rdflib.term.URIRef('urn:cake')

  New in version 4.0.

  `__getitem__`(name)

    Return self[key].

  static `__new__`(cls, values, labels)

    Create and return a new object. See help(type) for accurate signature.

class `rdflib.query.``Processor`(graph)

  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.

  `__init__`(graph)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.query'
  `query`(strOrQuery, initBindings={}, initNs={}, DEBUG=False)

class `rdflib.query.``Result`(type_)

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

  `__bool__`()
  `__eq__`(other)

    Return self==value.

  `__getattr__`(name)
  `__hash__` = None
  `__init__`(type_)

    Initialize self. See help(type(self)) for accurate signature.

  `__iter__`()
  `__len__`()
  `__module__` = 'rdflib.query'
  `bindings`

    a list of variable bindings as dicts

  static `parse`(source, format='xml', **kwargs)
  `serialize`(destination=None, encoding='utf-8', format='xml', **args)

class `rdflib.query.``ResultParser`

  Bases: `object`

  `__init__`()

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.query'
  `parse`(source, **kwargs)

    return a Result object

class `rdflib.query.``ResultSerializer`(result)

  Bases: `object`

  `__init__`(result)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.query'
  `serialize`(stream, encoding='utf-8', **kwargs)

    return a string properly serialized

exception `rdflib.query.``ResultException`

  Bases: `Exception`

  `__module__` = 'rdflib.query'

## `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`s and :class:`rdflib.term.BNode`s) are in turn wrapped as Resources. (Note that this behaviour differs from the corresponding methods in :class:`~rdflib.graph.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('http://example.org/person/some1#self')

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

    >>> person.value(RDFS.comment)
    rdflib.term.Literal('Just a Python & RDF hacker.', lang='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:

    >>> str(person)
    '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()
    'foaf:Person'

Or for the predicates of a resource:

    >>> sorted(
    ...     p.qname() for p in person.predicates()
    ... )
    ['foaf:depiction', 'foaf:homepage',
     'foaf:name', 'rdf:type', '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.label())
    ...     print(pic.comment())
    ...     print(pic.value(FOAF.thumbnail).identifier)
    http://example.org/images/person/some1.jpg
    foaf:Image
    some 1
    Just an 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

Similarly, adding, setting and removing data is easy:

    >>> thumb.add(RDFS.label, Literal("thumb"))
    >>> print(thumb.label())
    thumb
    >>> thumb.set(RDFS.label, Literal("thumbnail"))
    >>> print(thumb.label())
    thumbnail
    >>> thumb.remove(RDFS.label)
    >>> list(thumb.objects(RDFS.label))
    []

### 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]
    ['v:Artifact', 'v:Document', 'v:Paper']

and superclasses from the last subclass:

    >>> [c.qname() for c in subclasses[-1].transitive_objects(RDFS.subClassOf)]
    ['v:Paper', 'v:Document', '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()]
    ['v:One', 'v:Other']

And the sequence of Stuff:

    >>> stuff = Resource(graph, URIRef("http://example.org/def/v#Stuff"))
    >>> [it.qname() for it in stuff.seq()]
    ['v:One', '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)

  Bases: `object`

  `__eq__`(other)

    Return self==value.

  `__ge__`(other)
  `__getitem__`(item)
  `__gt__`(other)
  `__hash__`()

    Return hash(self).

  `__init__`(graph, subject)

    Initialize self. See help(type(self)) for accurate signature.

  `__iter__`()
  `__le__`(other)
  `__lt__`(other)

    Return self<value.

  `__module__` = 'rdflib.resource'
  `__ne__`(other)
  `__repr__`()

    Return repr(self).

  `__setitem__`(item, value)
  `__str__`()

    Return str(self).

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

## `serializer` Module

Serializer plugin interface.

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

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

class `rdflib.serializer.``Serializer`(store)

  Bases: `object`

  `__init__`(store)

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.serializer'
  `relativize`(uri)
  `serialize`(stream, base=None, encoding=None, **args)

    Abstract method

## `store` Module

### rdflib.store

#### Types of store

`Context-aware`: An RDF store capable of storing statements within contexts is considered context-aware. Essentially, such a store is able to partition the RDF model it represents into individual, named, and addressable sub-graphs.

Relevant Notation3 reference regarding formulae, quoted statements, and such: http://www.w3.org/DesignIssues/Notation3.html

`Formula-aware`: An RDF store capable of distinguishing between statements that are asserted and statements that are quoted is considered formula-aware.

`Transaction-capable`: capable of providing transactional integrity to the RDF operations performed on it.

`Graph-aware`: capable of keeping track of empty graphs.

class `rdflib.store.``StoreCreatedEvent`(**kw)

  Bases: `rdflib.events.Event`

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

  > - `configuration`: string used to create the store

  `__module__` = 'rdflib.store'

class `rdflib.store.``TripleAddedEvent`(**kw)

  Bases: `rdflib.events.Event`

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

  > - the `triple` added to the graph
  > - the `context` of the triple, if any
  > - the `graph` to which the triple was added

  `__module__` = 'rdflib.store'

class `rdflib.store.``TripleRemovedEvent`(**kw)

  Bases: `rdflib.events.Event`

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

  > - the `triple` removed from the graph
  > - the `context` of the triple, if any
  > - the `graph` from which the triple was removed

  `__module__` = 'rdflib.store'

class `rdflib.store.``NodePickler`

  Bases: `object`

  `__getstate__`()
  `__init__`()

    Initialize self. See help(type(self)) for accurate signature.

  `__module__` = 'rdflib.store'
  `__setstate__`(state)
  `dumps`(obj, protocol=None, bin=None)
  `loads`(s)
  `register`(object, id)

class `rdflib.store.``Store`(configuration=None, identifier=None)

  Bases: `object`

  `__init__`(configuration=None, identifier=None)

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

  `__len__`(context=None)

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

    Parameters: | context – a graph instance to query or None

  `__module__` = 'rdflib.store'
  `add`(xxx_todo_changeme, context, quoted=False)

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

  `addN`(quads)

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

  `add_graph`(graph)

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

  `bind`(prefix, namespace)
  `close`(commit_pending_transaction=False)

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

  `commit`()
  `context_aware` = False
  `contexts`(triple=None)

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

    if store is graph_aware, may also return empty contexts

    Returns: | a generator over Nodes

  `create`(configuration)
  `destroy`(configuration)

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

  `formula_aware` = False
  `gc`()

    Allows the store to perform any needed garbage collection

  `graph_aware` = False
  `namespace`(prefix)
  `namespaces`()
  `node_pickler`
  `open`(configuration, create=False)

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

  `prefix`(namespace)
  `query`(query, initNs, initBindings, queryGraph, **kwargs)

    If stores provide their own SPARQL implementation, override this.

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

  `remove`(xxx_todo_changeme1, context=None)

    Remove the set of triples matching the pattern from the store

  `remove_graph`(graph)

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

    Parameters: | graphid – a Graph instance

  `rollback`()
  `transaction_aware` = False
  `triples`(triple_pattern, context=None)

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

    Parameters: | context – A conjunctive query can be indicated by either

    providing a value of None, or a specific context can be queries by passing a Graph instance (if store is context aware).

  `triples_choices`(xxx_todo_changeme2, context=None)

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

  `update`(update, initNs, initBindings, queryGraph, **kwargs)

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

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

## `term` Module

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

- `Blank Nodes`
- `URI References`
- `Literals` (which consist of a literal value,datatype and language tag)

Those that extend the RDF model into N3:

- `Formulae`
- `Universal Quantifications (Variables)`

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

- REGEX Expressions
- Date Ranges
- Numerical Ranges

`rdflib.term.``bind`(datatype, pythontype, constructor=None, lexicalizer=None)

  register a new datatype<->pythontype binding

  Parameters:

  - constructor – an optional function for converting lexical forms into a Python instances, if not given the pythontype is used directly
  - lexicalizer – an optinoal function for converting python objects to lexical form, if not given object.__str__ is used

class `rdflib.term.``Node`

  Bases: `object`

  A Node in the Graph.

  `__module__` = 'rdflib.term'
  `__slots__` = ()

class `rdflib.term.``Identifier`

  Bases: `rdflib.term.Node`, `str`

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

  `__eq__`(other)

    Equality for Nodes.

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

  `__ge__`(other)

    Return self>=value.

  `__gt__`(other)

    This implements ordering for Nodes,

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

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

  `__hash__`()

    Return hash(self).

  `__le__`(other)

    Return self<=value.

  `__lt__`(other)

    Return self<value.

  `__module__` = 'rdflib.term'
  `__ne__`(other)

    Return self!=value.

  static `__new__`(cls, value)

    Create and return a new object. See help(type) for accurate signature.

  `__slots__` = ()
  `eq`(other)

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

  `neq`(other)

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

class `rdflib.term.``URIRef`

  Bases: `rdflib.term.Identifier`

  RDF URI Reference: http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref

  `__add__`(other)

    Return self+value.

  `__getnewargs__`()
  `__invert__`()

    inverse path

  `__mod__`(other)

    Return self%value.

  `__module__` = 'rdflib.term'
  `__mul__`(mul)

    cardinality path

  `__neg__`()

    negated path

  static `__new__`(cls, value, base=None)

    Create and return a new object. See help(type) for accurate signature.

  `__or__`(other)

    alternative path

  `__radd__`(other)
  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `__slots__` = ()
  `__truediv__`(other)

    sequence path

  `de_skolemize`()

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

    New in version 4.0.

  `defrag`()
  `md5_term_hash`()

    a string of hex that will be the same for two URIRefs that are the same. It is not a suitable unique id.

    Supported for backwards compatibility; new code should probably just use __hash__

  `n3`(namespace_manager=None)

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

    Parameters: | namespace_manager – if not None, will be used to make up a prefixed name

  `toPython`()

class `rdflib.term.``BNode`

  Bases: `rdflib.term.Identifier`

  Blank Node: http://www.w3.org/TR/rdf-concepts/#section-blank-nodes

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

    # only store implementations should pass in a value

  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `__slots__` = ()
  `md5_term_hash`()

    a string of hex that will be the same for two BNodes that are the same. It is not a suitable unique id.

    Supported for backwards compatibility; new code should probably just use __hash__

  `n3`(namespace_manager=None)
  `skolemize`(authority='http://rdlib.net/')

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

    New in version 4.0.

  `toPython`()

class `rdflib.term.``Literal`

  Bases: `rdflib.term.Identifier`

  RDF Literal: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal

  The lexical value of the literal is the unicode object The interpreted, datatyped value is available from .value

  Language tags must be valid according to :rfc:5646

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

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

      >>> from rdflib.namespace import XSD

      >>> Literal('01')!=Literal('1') # clear - strings differ
      True

  but with data-type they get normalized:

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

  unless disabled:

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

  Value based comparison is possible:

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

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

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

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

  Any comparison with non-rdflib Node are “NotImplemented” In PY2.X some stable order will be made up by python

  In PY3 this is an error.

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

  The > < operators will eat this NotImplemented and either make up an ordering (py2.x) or throw a TypeError (py3k):

      >>> Literal(1).__gt__(2.0)
      NotImplemented

  `__abs__`()

        >>> abs(Literal(-1))
        rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))

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

        >>> abs(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal('1')

  `__add__`(val)

        >>> Literal(1) + 1
        rdflib.term.Literal('2', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
        >>> Literal("1") + "1"
        rdflib.term.Literal('11')

  `__bool__`()

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

  `__eq__`(other)

    Literals are only equal to other literals.

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

        >>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo"))
        True
        >>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo2"))
        False

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

  `__ge__`(other)

    Return self>=value.

  `__getstate__`()
  `__gt__`(other)

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

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

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

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

    Incompatible datatype mismatches ordered by DT

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

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

  `__hash__`()

        >>> from rdflib.namespace import XSD
        >>> a = {Literal('1', datatype=XSD.integer):'one'}
        >>> Literal('1', datatype=XSD.double) in a
        False

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

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

  `__invert__`()

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

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

    Not working:

        >>> ~(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal('1')

  `__le__`(other)

        >>> from rdflib.namespace import XSD
        >>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
        ...     ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
        True

  `__lt__`(other)

    Return self<value.

  `__module__` = 'rdflib.term'
  `__neg__`()

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

        >>> (- Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal('1')
        >>>

  static `__new__`(cls, lexical_or_value, lang=None, datatype=None, normalize=None)

    Create and return a new object. See help(type) for accurate signature.

  `__pos__`()

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

        >>> (+ Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal('1')

  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `__setstate__`(arg)
  `__slots__` = ('_language', '_datatype', '_value')
  `datatype`
  `eq`(other)

    Compare the value of this literal with something else

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

    OR, with a python object:

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

    bool objects with xsd:boolean

    a int, long or float with numeric xsd types

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

    Any other operations returns NotImplemented

  `language`
  `md5_term_hash`()

    a string of hex that will be the same for two Literals that are the same. It is not a suitable unique id.

    Supported for backwards compatibility; new code should probably just use __hash__

  `n3`(namespace_manager=None)

    Returns a representation in the N3 format.

    Examples:

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

    Strings with newlines or triple-quotes:

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

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

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

    Language:

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

    Datatypes:

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

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

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

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

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

    Custom datatype:

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

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

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

  `neq`(other)

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

  `normalize`()

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

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

  `toPython`()

    Returns an appropriate python datatype derived from this RDF Literal

  `value`

class `rdflib.term.``Variable`

  Bases: `rdflib.term.Identifier`

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

  `__module__` = 'rdflib.term'
  static `__new__`(cls, value)

    Create and return a new object. See help(type) for accurate signature.

  `__reduce__`()

    Helper for pickle.

  `__repr__`()

    Return repr(self).

  `__slots__` = ()
  `md5_term_hash`()

    a string of hex that will be the same for two Variables that are the same. It is not a suitable unique id.

    Supported for backwards compatibility; new code should probably just use __hash__

  `n3`(namespace_manager=None)
  `toPython`()

class `rdflib.term.``Statement`

  Bases: `rdflib.term.Node`, `tuple`

  `__module__` = 'rdflib.term'
  static `__new__`(cls, xxx_todo_changeme, context)

    Create and return a new object. See help(type) for accurate signature.

  `__reduce__`()

    Helper for pickle.

  `toPython`()

## `util` Module

Some utility functions.

Miscellaneous utilities

- list2set
- first
- uniq
- more_than

Term characterisation and generation

- to_term
- from_n3

Date/time utilities

- date_time
- parse_date_time

Statement and component type checkers

- check_context
- check_subject
- check_predicate
- check_object
- check_statement
- check_pattern

`rdflib.util.``list2set`(seq)

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

`rdflib.util.``first`(seq)

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

`rdflib.util.``uniq`(sequence, strip=0)

  removes duplicate strings from the sequence.

`rdflib.util.``more_than`(sequence, number)

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

`rdflib.util.``to_term`(s, default=None)

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

  ‘’ returns the `default` keyword argument value or `None`

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

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

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

`rdflib.util.``from_n3`(s, default=None, backend=None, nsm=None)

  Creates the Identifier corresponding to the given n3 string.

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

`rdflib.util.``date_time`(t=None, local_time_zone=False)

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

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

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

      >>> date_time(1)
      '1970-01-01T00:00:01Z'

      >>> date_time(0)
      '1970-01-01T00:00:00Z'

`rdflib.util.``parse_date_time`(val)

  always returns seconds in UTC

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

      >>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0
      0.0

      >>> parse_date_time('1970-01-01T00:00:01Z') - 1.0
      0.0

      >>> parse_date_time('1970-01-01T00:00:00Z') - 0.0
      0.0
      >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0
      0.0

`rdflib.util.``check_context`(c)

`rdflib.util.``check_subject`(s)

  Test that s is a valid subject identifier.

`rdflib.util.``check_predicate`(p)

  Test that p is a valid predicate identifier.

`rdflib.util.``check_object`(o)

  Test that o is a valid object identifier.

`rdflib.util.``check_statement`(triple)

`rdflib.util.``check_pattern`(triple)

`rdflib.util.``guess_format`(fpath, fmap=None)

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

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

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

      >>> guess_format('.rdf')
      'xml'
      >>> guess_format('rdf')
      'xml'
      >>> guess_format('RDF')
      'xml'

`rdflib.util.``find_roots`(graph, prop, roots=None)

  Find the roots in some sort of transitive hierarchy.

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

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

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

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

  i.e.

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

  will return the structure for the subClassTree below person.

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

## `void` Module

`rdflib.void.``generateVoID`(g, dataset=None, res=None, distinctForPartitions=True)

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

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

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

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

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

## Subpackages

- extras Package
  - `extras` Package
  - `cmdlineutils` Module
  - `describer` Module
  - `infixowl` Module
- plugins Package
  - `plugins` Package
  - `memory` Module
  - `sleepycat` Module
  - Subpackages
    - parsers Package
      - `parsers` Package
      - `hturtle` Module
      - `notation3` Module
      - `nquads` Module
      - `nt` Module
      - `ntriples` Module
      - `rdfxml` Module
      - `structureddata` Module
      - `trix` Module
      - Subpackages
        - pyMicrodata Package
          - `pyMicrodata` Package
            - (Simple) Usage
              - Return formats
          - `microdata` Module
          - `registry` Module
          - `utils` Module
        - pyRdfa Package
          - `pyRdfa` Package
            - (Simple) Usage
              - Return (serialization) formats
            - Options
            - Host Languages
            - Vocabularies
              - Vocabulary caching
            - RDFa 1.1 vs. RDFa 1.0
            - Transformers
          - `embeddedRDF` Module
          - `initialcontext` Module
          - `options` Module
          - `parse` Module
          - `property` Module
          - `state` Module
          - `termorcurie` Module
          - `utils` Module
          - Subpackages
            - extras Package
              - `extras` Package
              - `httpheader` Module
            - host Package
              - `host` Package
              - `atom` Module
              - `html5` Module
            - rdfs Package
              - `rdfs` Package
              - `cache` Module
              - `process` Module
            - transform Package
              - `transform` Package
              - `DublinCore` Module
              - `OpenID` Module
              - `lite` Module
              - `metaname` Module
              - `prototype` Module
    - serializers Package
      - `n3` Module
      - `nquads` Module
      - `nt` Module
      - `rdfxml` Module
      - `trig` Module
      - `trix` Module
      - `turtle` Module
      - `xmlwriter` Module
    - sparql Package
      - `sparql` Package
      - `aggregates` Module
      - `algebra` Module
      - `compat` Module
      - `datatypes` Module
      - `evaluate` Module
      - `evalutils` Module
      - `operators` Module
      - `parser` Module
      - `parserutils` Module
      - `processor` Module
      - `sparql` Module
      - `update` Module
      - Subpackages
        - results Package
          - `csvresults` Module
          - `jsonlayer` Module
          - `jsonresults` Module
          - `rdfresults` Module
          - `tsvresults` Module
          - `xmlresults` Module
    - stores Package
      - `stores` Package
      - `auditable` Module
      - `concurrent` Module
      - `regexmatching` Module
      - `sparqlstore` Module
- tools Package
  - `tools` Package
  - `csv2rdf` Module
  - `graphisomorphism` Module
  - `rdf2dot` Module
  - `rdfpipe` Module
  - `rdfs2dot` Module