Skip to content

# `` graph

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

Deprecation notice

`ConjunctiveGraph` is deprecated, use `Dataset` instead.

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

See `ConjunctiveGraph`

### Quoted graph

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

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

See `QuotedGraph`

### Dataset

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

See `Dataset`

### Working with graphs

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

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

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

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

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

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

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

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

    >>> for s, p, o in g.triples((None, RDF.object, None)):
    ...     print(o)
    ...
    Conjunctive Graph
    >>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
    >>> print(len(g))
    3

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

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

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

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

Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store:

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

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

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

Parsing N3 from a string:

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

Using Namespace class:

    >>> RDFLib = Namespace("https://rdflib.github.io/")
    >>> RDFLib.ConjunctiveGraph
    rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
    >>> RDFLib["Graph"]
    rdflib.term.URIRef('https://rdflib.github.io/Graph')

Classes:

- `BatchAddGraph` –

  Wrapper around graph that turns batches of calls to Graph’s add

- `ConjunctiveGraph` –

  A ConjunctiveGraph is an (unnamed) aggregation of all the named

- `Dataset` –

  An RDFLib Dataset is an object that stores multiple Named Graphs - instances of

- `Graph` –

  An RDF Graph: a Python object containing nodes and relations between them as

- `ModificationException` –
- `QuotedGraph` –

  Quoted Graphs are intended to implement Notation 3 formulae. They are

- `ReadOnlyGraphAggregate` –

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

- `Seq` –

  Wrapper around an RDF Seq resource

- `UnSupportedAggregateOperation` –

## `` DATASET_DEFAULT_GRAPH_ID `module-attribute`

    DATASET_DEFAULT_GRAPH_ID = URIRef('urn:x-rdflib:default')

## `` __all__ `module-attribute`

    __all__ = ['Graph', 'ConjunctiveGraph', 'QuotedGraph', 'Seq', 'ModificationException', 'Dataset', 'UnSupportedAggregateOperation', 'ReadOnlyGraphAggregate', 'BatchAddGraph', '_ConjunctiveGraphT', '_ContextIdentifierType', '_DatasetT', '_GraphT', '_ObjectType', '_OptionalIdentifiedQuadType', '_OptionalQuadType', '_PredicateType', '_QuadPathPatternType', '_QuadPatternType', '_QuadSelectorType', '_QuadType', '_SubjectType', '_TripleOrOptionalQuadType', '_TripleOrTriplePathType', '_TripleOrQuadPathPatternType', '_TripleOrQuadPatternType', '_TripleOrQuadSelectorType', '_TriplePathPatternType', '_TriplePathType', '_TriplePatternType', '_TripleSelectorType', '_TripleType']

## `` logger `module-attribute`

    logger = getLogger(__name__)

## `` BatchAddGraph

    BatchAddGraph(graph: Graph, batch_size: int = 1000, batch_addn: bool = False)

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

Parameters:

- ### `graph`

  (`Graph`) –

  The graph to wrap

- ### `batch_size`

  (`int`, default: `1000` ) –

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

- ### `batch_addn`

  (`bool`, default: `False` ) –

  If True, then even calls to `addN` will be batched according to batch_size

Attributes:

- `graph` –

  The wrapped graph

- `count` –

  The number of triples buffered since initialization or the last call to reset

- `batch` –

  The current buffer of triples

Methods:

- `__enter__` –
- `__exit__` –
- `add` –

  Add a triple to the buffer.

- `addN` –
- `reset` –

  Manually clear the buffered triples and reset the count to zero

Source code in `rdflib/graph.py`

    3343
    3344
    3345
    3346
    3347
    3348
    3349
    3350

    def __init__(self, graph: Graph, batch_size: int = 1000, batch_addn: bool = False):
        if not batch_size or batch_size < 2:
            raise ValueError("batch_size must be a positive number")
        self.graph = graph
        self.__graph_tuple = (graph,)
        self.__batch_size = batch_size
        self.__batch_addn = batch_addn
        self.reset()

### `` __batch_addn `instance-attribute`

    __batch_addn = batch_addn

### `` __batch_size `instance-attribute`

    __batch_size = batch_size

### `` __graph_tuple `instance-attribute`

    __graph_tuple = (graph,)

### `` graph `instance-attribute`

    graph = graph

### `` __enter__

    __enter__() -> BatchAddGraph

Source code in `rdflib/graph.py`

    3395
    3396
    3397

    def __enter__(self) -> BatchAddGraph:
        self.reset()
        return self

### `` __exit__

    __exit__(*exc) -> None

Source code in `rdflib/graph.py`

    3399
    3400
    3401

    def __exit__(self, *exc) -> None:
        if exc[0] is None:
            self.graph.addN(self.batch)

### `` add

    add(triple_or_quad: Union[_TripleType, _QuadType]) -> BatchAddGraph

Add a triple to the buffer.

Parameters:

- #### `triple_or_quad`

  (`Union[_TripleType, _QuadType]`) –

  The triple or quad to add

Returns:

- `BatchAddGraph` –

  The BatchAddGraph instance

Source code in `rdflib/graph.py`

    3360
    3361
    3362
    3363
    3364
    3365
    3366
    3367
    3368
    3369
    3370
    3371
    3372
    3373
    3374
    3375
    3376
    3377
    3378
    3379
    3380
    3381
    3382
    3383
    3384
    3385

    def add(
        self,
        triple_or_quad: Union[
            _TripleType,
            _QuadType,
        ],
    ) -> BatchAddGraph:
        """Add a triple to the buffer.

        Args:
            triple_or_quad: The triple or quad to add

        Returns:
            The BatchAddGraph instance
        """
        if len(self.batch) >= self.__batch_size:
            self.graph.addN(self.batch)
            self.batch = []
        self.count += 1
        if len(triple_or_quad) == 3:
            # type error: Argument 1 to "append" of "list" has incompatible type "Tuple[Node, ...]"; expected "Tuple[Node, Node, Node, Graph]"
            self.batch.append(triple_or_quad + self.__graph_tuple)  # type: ignore[arg-type, unused-ignore]
        else:
            # type error: Argument 1 to "append" of "list" has incompatible type "Union[Tuple[Node, Node, Node], Tuple[Node, Node, Node, Graph]]"; expected "Tuple[Node, Node, Node, Graph]"
            self.batch.append(triple_or_quad)  # type: ignore[arg-type, unused-ignore]
        return self

### `` addN

    addN(quads: Iterable[_QuadType]) -> BatchAddGraph

Source code in `rdflib/graph.py`

    3387
    3388
    3389
    3390
    3391
    3392
    3393

    def addN(self, quads: Iterable[_QuadType]) -> BatchAddGraph:  # noqa: N802
        if self.__batch_addn:
            for q in quads:
                self.add(q)
        else:
            self.graph.addN(quads)
        return self

### `` reset

    reset() -> BatchAddGraph

Manually clear the buffered triples and reset the count to zero

Source code in `rdflib/graph.py`

    3352
    3353
    3354
    3355
    3356
    3357
    3358

    def reset(self) -> BatchAddGraph:
        """
        Manually clear the buffered triples and reset the count to zero
        """
        self.batch: List[_QuadType] = []
        self.count = 0
        return self

## `` ConjunctiveGraph

    ConjunctiveGraph(store: Union[Store, str] = 'default', identifier: Optional[Union[IdentifiedNode, str]] = None, default_graph_base: Optional[str] = None)

Bases: `Graph`

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

Deprecation notice

ConjunctiveGraph is deprecated, use `rdflib.graph.Dataset` instead.

It has a `default` graph, whose name is associated with the graph throughout its life. Constructor 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.

Methods:

- `__contains__` –

  Support for ‘triple/quad in graph’ syntax

- `__len__` –

  Number of triples in the entire conjunctive graph

- `__reduce__` –
- `__str__` –
- `add` –

  Add a triple or quad to the store.

- `addN` –

  Add a sequence of triples with context

- `context_id` –

  URI#context

- `contexts` –

  Iterate over all contexts in the graph

- `get_context` –

  Return a context graph for the given identifier

- `get_graph` –

  Returns the graph identified by given identifier

- `parse` –

  Parse source adding the resulting triples to its own context (sub graph

- `quads` –

  Iterate over all the quads in the entire conjunctive graph

- `remove` –

  Removes a triple or quads

- `remove_context` –

  Removes the given context from the graph

- `triples` –

  Iterate over all the triples in the entire conjunctive graph

- `triples_choices` –

  Iterate over all the triples in the entire conjunctive graph

Attributes:

- `context_aware` –
- `default_context` –
- `default_union` –

Source code in `rdflib/graph.py`

    2135
    2136
    2137
    2138
    2139
    2140
    2141
    2142
    2143
    2144
    2145
    2146
    2147
    2148
    2149
    2150
    2151
    2152
    2153
    2154
    2155
    2156
    2157

    def __init__(
        self,
        store: Union[Store, str] = "default",
        identifier: Optional[Union[IdentifiedNode, str]] = None,
        default_graph_base: Optional[str] = None,
    ):
        super(ConjunctiveGraph, self).__init__(store, identifier=identifier)

        if type(self) is ConjunctiveGraph:
            warnings.warn(
                "ConjunctiveGraph is deprecated, use Dataset instead.",
                DeprecationWarning,
                stacklevel=2,
            )

        assert self.store.context_aware, (
            "ConjunctiveGraph must be backed by" " a context aware store."
        )
        self.context_aware = True
        self.default_union = True  # Conjunctive!
        self._default_context: _ContextType = Graph(
            store=self.store, identifier=identifier or BNode(), base=default_graph_base
        )

### `` context_aware `instance-attribute`

    context_aware = True

### `` default_context `property` `writable`

    default_context

### `` default_union `instance-attribute`

    default_union = True

### `` __contains__

    __contains__(triple_or_quad: _TripleOrQuadSelectorType) -> bool

Support for ‘triple/quad in graph’ syntax

Source code in `rdflib/graph.py`

    2237
    2238
    2239
    2240
    2241
    2242

    def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool:
        """Support for 'triple/quad in graph' syntax"""
        s, p, o, c = self._spoc(triple_or_quad)
        for t in self.triples((s, p, o), context=c):
            return True
        return False

### `` __len__

    __len__() -> int

Number of triples in the entire conjunctive graph

Source code in `rdflib/graph.py`

    2384
    2385
    2386

    def __len__(self) -> int:
        """Number of triples in the entire conjunctive graph"""
        return self.store.__len__()

### `` __reduce__

    __reduce__() -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]

Source code in `rdflib/graph.py`

    2512
    2513

    def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
        return ConjunctiveGraph, (self.store, self.identifier)

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    2167
    2168
    2169
    2170
    2171
    2172

    def __str__(self) -> str:
        pattern = (
            "[a rdflib:ConjunctiveGraph;rdflib:storage "
            "[a rdflib:Store;rdfs:label '%s']]"
        )
        return pattern % self.store.__class__.__name__

### `` add

    add(triple_or_quad: _TripleOrOptionalQuadType) -> _ConjunctiveGraphT

Add a triple or quad to the store.

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

Source code in `rdflib/graph.py`

    2244
    2245
    2246
    2247
    2248
    2249
    2250
    2251
    2252
    2253
    2254
    2255
    2256
    2257
    2258
    2259

    def add(
        self: _ConjunctiveGraphT,
        triple_or_quad: _TripleOrOptionalQuadType,
    ) -> _ConjunctiveGraphT:
        """Add a triple or quad to the store.

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

        s, p, o, c = self._spoc(triple_or_quad, default=True)

        _assertnode(s, p, o)

        # type error: Argument "context" to "add" of "Store" has incompatible type "Optional[Graph]"; expected "Graph"
        self.store.add((s, p, o), context=c, quoted=False)  # type: ignore[arg-type]
        return self

### `` addN

    addN(quads: Iterable[_QuadType]) -> _ConjunctiveGraphT

Add a sequence of triples with context

Source code in `rdflib/graph.py`

    2281
    2282
    2283
    2284
    2285
    2286
    2287
    2288
    2289

    def addN(  # noqa: N802
        self: _ConjunctiveGraphT, quads: Iterable[_QuadType]
    ) -> _ConjunctiveGraphT:
        """Add a sequence of triples with context"""

        self.store.addN(
            (s, p, o, self._graph(c)) for s, p, o, c in quads if _assertnode(s, p, o)
        )
        return self

### `` context_id

    context_id(uri: str, context_id: Optional[str] = None) -> URIRef

URI#context

Source code in `rdflib/graph.py`

    2430
    2431
    2432
    2433
    2434
    2435

    def context_id(self, uri: str, context_id: Optional[str] = None) -> URIRef:
        """URI#context"""
        uri = uri.split("#", 1)[0]
        if context_id is None:
            context_id = "#context"
        return URIRef(context_id, base=uri)

### `` contexts

    contexts(triple: Optional[_TripleType] = None) -> Generator[_ContextType, None, None]

Iterate over all contexts in the graph

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

Source code in `rdflib/graph.py`

    2388
    2389
    2390
    2391
    2392
    2393
    2394
    2395
    2396
    2397
    2398
    2399
    2400
    2401
    2402
    2403

    def contexts(
        self, triple: Optional[_TripleType] = None
    ) -> Generator[_ContextType, None, None]:
        """Iterate over all contexts in the graph

        If triple is specified, iterate over all contexts the triple is in.
        """
        for context in self.store.contexts(triple):
            if isinstance(context, Graph):
                # TODO: One of these should never happen and probably
                # should raise an exception rather than smoothing over
                # the weirdness - see #225
                yield context
            else:
                # type error: Statement is unreachable
                yield self.get_context(context)  # type: ignore[unreachable]

### `` get_context

    get_context(identifier: Optional[Union[_ContextIdentifierType, str]], quoted: bool = False, base: Optional[str] = None) -> Graph

Return a context graph for the given identifier

identifier must be a URIRef or BNode.

Source code in `rdflib/graph.py`

    2409
    2410
    2411
    2412
    2413
    2414
    2415
    2416
    2417
    2418
    2419
    2420
    2421
    2422
    2423
    2424

    def get_context(
        self,
        identifier: Optional[Union[_ContextIdentifierType, str]],
        quoted: bool = False,
        base: Optional[str] = None,
    ) -> Graph:
        """Return a context graph for the given identifier

        identifier must be a URIRef or BNode.
        """
        return Graph(
            store=self.store,
            identifier=identifier,
            namespace_manager=self.namespace_manager,
            base=base,
        )

### `` get_graph

    get_graph(identifier: _ContextIdentifierType) -> Union[Graph, None]

Returns the graph identified by given identifier

Source code in `rdflib/graph.py`

    2405
    2406
    2407

    def get_graph(self, identifier: _ContextIdentifierType) -> Union[Graph, None]:
        """Returns the graph identified by given identifier"""
        return [x for x in self.contexts() if x.identifier == identifier][0]

### `` parse

    parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Graph

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

See `rdflib.graph.Graph.parse` for documentation on arguments.

Parameters:

- #### `source`

  (`Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]]`, default: `None` ) –

  The source to parse

- #### `publicID`

  (`Optional[str]`, default: `None` ) –

  The public ID of the source

- #### `format`

  (`Optional[str]`, default: `None` ) –

  The format of the source

- #### `location`

  (`Optional[str]`, default: `None` ) –

  The location of the source

- #### `file`

  (`Optional[Union[BinaryIO, TextIO]]`, default: `None` ) –

  The file object to parse

- #### `data`

  (`Optional[Union[str, bytes]]`, default: `None` ) –

  The data to parse

- #### `**args`

  (`Any`, default: `{}` ) –

  Additional arguments

Returns:

- `Graph` –

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

- `Graph` –

  the root context.

Note

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

Caution

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

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

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

Changed in 7.0

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

Source code in `rdflib/graph.py`

    2437
    2438
    2439
    2440
    2441
    2442
    2443
    2444
    2445
    2446
    2447
    2448
    2449
    2450
    2451
    2452
    2453
    2454
    2455
    2456
    2457
    2458
    2459
    2460
    2461
    2462
    2463
    2464
    2465
    2466
    2467
    2468
    2469
    2470
    2471
    2472
    2473
    2474
    2475
    2476
    2477
    2478
    2479
    2480
    2481
    2482
    2483
    2484
    2485
    2486
    2487
    2488
    2489
    2490
    2491
    2492
    2493
    2494
    2495
    2496
    2497
    2498
    2499
    2500
    2501
    2502
    2503
    2504
    2505
    2506
    2507
    2508
    2509
    2510

    def parse(
        self,
        source: Optional[
            Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
        ] = None,
        publicID: Optional[str] = None,  # noqa: N803
        format: Optional[str] = None,
        location: Optional[str] = None,
        file: Optional[Union[BinaryIO, TextIO]] = None,
        data: Optional[Union[str, bytes]] = None,
        **args: Any,
    ) -> Graph:
        """Parse source adding the resulting triples to its own context (sub graph
        of this graph).

        See [`rdflib.graph.Graph.parse`][rdflib.graph.Graph.parse] for documentation on arguments.

        Args:
            source: The source to parse
            publicID: The public ID of the source
            format: The format of the source
            location: The location of the source
            file: The file object to parse
            data: The data to parse
            **args: Additional arguments

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

        Note:
            If the source is in a format that does not support named graphs its triples
            will be added to the default graph (i.e. ConjunctiveGraph.default_context).

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

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

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

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

        source = create_input_source(
            source=source,
            publicID=publicID,
            location=location,
            file=file,
            data=data,
            format=format,
        )

        # NOTE on type hint: `xml.sax.xmlreader.InputSource.getPublicId` has no
        # type annotations but given that systemId should be a string, and
        # given that there is no specific mention of type for publicId, it
        # seems reasonable to assume it should also be a string. Furthermore,
        # create_input_source will ensure that publicId is not None, though it
        # would be good if this guarantee was made more explicit i.e. by type
        # hint on InputSource (TODO/FIXME).

        context = self.default_context
        context.parse(source, publicID=publicID, format=format, **args)
        return self

### `` quads

    quads(triple_or_quad: Optional[_TripleOrQuadPatternType] = None) -> Generator[_OptionalQuadType, None, None]

Iterate over all the quads in the entire conjunctive graph

Source code in `rdflib/graph.py`

    2356
    2357
    2358
    2359
    2360
    2361
    2362
    2363
    2364
    2365

    def quads(
        self, triple_or_quad: Optional[_TripleOrQuadPatternType] = None
    ) -> Generator[_OptionalQuadType, None, None]:
        """Iterate over all the quads in the entire conjunctive graph"""

        s, p, o, c = self._spoc(triple_or_quad)

        for (s, p, o), cg in self.store.triples((s, p, o), context=c):
            for ctx in cg:
                yield s, p, o, ctx

### `` remove

    remove(triple_or_quad: _TripleOrOptionalQuadType) -> _ConjunctiveGraphT

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

Source code in `rdflib/graph.py`

    2292
    2293
    2294
    2295
    2296
    2297
    2298
    2299
    2300
    2301

    def remove(self: _ConjunctiveGraphT, triple_or_quad: _TripleOrOptionalQuadType) -> _ConjunctiveGraphT:  # type: ignore[override]
        """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
        """
        s, p, o, c = self._spoc(triple_or_quad)

        self.store.remove((s, p, o), context=c)
        return self

### `` remove_context

    remove_context(context: _ContextType) -> None

Removes the given context from the graph

Source code in `rdflib/graph.py`

    2426
    2427
    2428

    def remove_context(self, context: _ContextType) -> None:
        """Removes the given context from the graph"""
        self.store.remove((None, None, None), context)

### `` triples

    triples(triple_or_quad: _TripleOrQuadSelectorType, context: Optional[_ContextType] = None) -> Generator[_TripleOrTriplePathType, None, None]

Iterate over all the triples in the entire conjunctive graph

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

Source code in `rdflib/graph.py`

    2324
    2325
    2326
    2327
    2328
    2329
    2330
    2331
    2332
    2333
    2334
    2335
    2336
    2337
    2338
    2339
    2340
    2341
    2342
    2343
    2344
    2345
    2346
    2347
    2348
    2349
    2350
    2351
    2352
    2353
    2354

    def triples(
        self,
        triple_or_quad: _TripleOrQuadSelectorType,
        context: Optional[_ContextType] = None,
    ) -> Generator[_TripleOrTriplePathType, None, None]:
        """Iterate over all the triples in the entire conjunctive graph

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

        s, p, o, c = self._spoc(triple_or_quad)
        context = self._graph(context or c)

        if self.default_union:
            if context == self.default_context:
                context = None
        else:
            if context is None:
                context = self.default_context

        if isinstance(p, Path):
            if context is None:
                context = self

            for s, o in p.eval(context, s, o):
                yield s, p, o
        else:
            for (s, p, o), cg in self.store.triples((s, p, o), context=context):
                yield s, p, o

### `` triples_choices

    triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]

Iterate over all the triples in the entire conjunctive graph

Source code in `rdflib/graph.py`

    2367
    2368
    2369
    2370
    2371
    2372
    2373
    2374
    2375
    2376
    2377
    2378
    2379
    2380
    2381
    2382

    def triples_choices(
        self,
        triple: _TripleChoiceType,
        context: Optional[_ContextType] = None,
    ) -> Generator[_TripleType, None, None]:
        """Iterate over all the triples in the entire conjunctive graph"""
        s, p, o = triple
        if context is None:
            if not self.default_union:
                context = self.default_context
        else:
            context = self._graph(context)
        # type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
        # type error note: unpacking discards type info
        for (s1, p1, o1), cg in self.store.triples_choices((s, p, o), context=context):  # type: ignore[arg-type]
            yield s1, p1, o1

## `` Dataset

    Dataset(store: Union[Store, str] = 'default', default_union: bool = False, default_graph_base: Optional[str] = None)

Bases: `ConjunctiveGraph`

An RDFLib Dataset is an object that stores multiple Named Graphs - instances of RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single Graph use.

RDFLib’s Dataset class is based on the RDF 1.2. ‘Dataset’ definition:

An RDF dataset is a collection of RDF graphs, and comprises:

- Exactly one default graph, being an RDF graph. The default graph does not have a name and MAY be empty.
- Zero or more named graphs. Each named graph is a pair consisting of an IRI or a blank node (the graph name), and an RDF graph. Graph names are unique within an RDF dataset.

Accordingly, a Dataset allows for `Graph` objects to be added to it with `URIRef` or `BNode` identifiers and always creats a default graph with the `URIRef` identifier `urn:x-rdflib:default`.

Dataset extends Graph’s Subject, Predicate, Object (s, p, o) ‘triple’ structure to include a graph identifier - archaically called Context - producing ‘quads’ of s, p, o, g.

Triples, or quads, can be added to a Dataset. Triples, or quads with the graph identifer :code:`urn:x-rdflib:default` go into the default graph.

Deprecation notice

Dataset builds on the `ConjunctiveGraph` class but that class’s direct use is now deprecated (since RDFLib 7.x) and it should not be used. `ConjunctiveGraph` will be removed from future RDFLib versions.

Examples of usage and see also the `examples/datast.py` file:

    >>> # 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")
    ... ))  # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>

    >>> # Create a graph in the dataset, if the graph name has already been
    >>> # used, the corresponding graph will be returned
    >>> # (ie, the Dataset keeps track of the constituent graphs)
    >>> g = ds.graph(URIRef("http://www.example.com/gr"))

    >>> # add triples to the new graph as usual
    >>> g.add((
    ...     URIRef("http://example.org/x"),
    ...     URIRef("http://example.org/y"),
    ...     Literal("bar")
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
    >>> # alternatively: add a quad to the dataset -> goes to the graph
    >>> ds.add((
    ...     URIRef("http://example.org/x"),
    ...     URIRef("http://example.org/z"),
    ...     Literal("foo-bar"),
    ...     g
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>

    >>> # 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
    >>> # (None) 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"))

    >>> # unrestricted looping is equivalent to iterating over the entire Dataset
    >>> for q in ds:  # 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"))

    >>> # resticting iteration to a graph:
    >>> 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.identifier)  # doctest:
    urn:x-rdflib: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
    https://rdflib.github.io/.well-known/genid/rdflib/N...
    http://www.example.com/gr
    >>> # Note that the Dataset.graphs() call returns names of empty graphs,
    >>> # too. This can be restricted:
    >>> for c in ds.graphs(empty=False):  # 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

Methods:

- `__getstate__` –
- `__iadd__` –

  Add all quads in Dataset other to Dataset.

- `__iter__` –

  Iterates over all quads in the store

- `__reduce__` –
- `__setstate__` –
- `__str__` –
- `add_graph` –

  alias of graph for consistency

- `contexts` –
- `graph` –
- `graphs` –
- `parse` –

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

- `quads` –
- `remove_graph` –
- `serialize` –

Attributes:

- `default_context` –
- `default_graph` –
- `default_union` –
- `identifier` –

Source code in `rdflib/graph.py`

    2673
    2674
    2675
    2676
    2677
    2678
    2679
    2680
    2681
    2682
    2683
    2684
    2685
    2686
    2687
    2688
    2689

    def __init__(
        self,
        store: Union[Store, str] = "default",
        default_union: bool = False,
        default_graph_base: Optional[str] = None,
    ):
        super(Dataset, self).__init__(store=store, identifier=None)

        if not self.store.graph_aware:
            raise Exception("Dataset must be backed by a graph-aware store!")
        self._default_context = Graph(
            store=self.store,
            identifier=DATASET_DEFAULT_GRAPH_ID,
            base=default_graph_base,
        )

        self.default_union = default_union

### `` default_context `property` `writable`

    default_context

### `` default_graph `property` `writable`

    default_graph

### `` default_union `instance-attribute`

    default_union = default_union

### `` identifier `property`

    identifier

### `` __getstate__

    __getstate__() -> Tuple[Store, _ContextIdentifierType, _ContextType, bool]

Source code in `rdflib/graph.py`

    2737
    2738

    def __getstate__(self) -> Tuple[Store, _ContextIdentifierType, _ContextType, bool]:
        return self.store, self.identifier, self.default_graph, self.default_union

### `` __iadd__

    __iadd__(other: Iterable[_QuadType]) -> _DatasetT

Add all quads in Dataset other to Dataset. BNode IDs are not changed.

Source code in `rdflib/graph.py`

    2747
    2748
    2749
    2750
    2751

    def __iadd__(self: _DatasetT, other: Iterable[_QuadType]) -> _DatasetT:  # type: ignore[override, misc]
        """Add all quads in Dataset other to Dataset.
        BNode IDs are not changed."""
        self.addN((s, p, o, g) for s, p, o, g in other)
        return self

### `` __iter__

    __iter__() -> Generator[_OptionalIdentifiedQuadType, None, None]

Iterates over all quads in the store

Source code in `rdflib/graph.py`

    2901
    2902
    2903
    2904
    2905

    def __iter__(  # type: ignore[override]
        self,
    ) -> Generator[_OptionalIdentifiedQuadType, None, None]:
        """Iterates over all quads in the store"""
        return self.quads((None, None, None, None))

### `` __reduce__

    __reduce__() -> Tuple[Type[Dataset], Tuple[Store, bool]]

Source code in `rdflib/graph.py`

    2734
    2735

    def __reduce__(self) -> Tuple[Type[Dataset], Tuple[Store, bool]]:  # type: ignore[override]
        return (type(self), (self.store, self.default_union))

### `` __setstate__

    __setstate__(state: Tuple[Store, _ContextIdentifierType, _ContextType, bool]) -> None

Source code in `rdflib/graph.py`

    2740
    2741
    2742
    2743
    2744
    2745

    def __setstate__(
        self, state: Tuple[Store, _ContextIdentifierType, _ContextType, bool]
    ) -> None:
        # type error: Property "store" defined in "Graph" is read-only
        # type error: Property "identifier" defined in "Graph" is read-only
        self.store, self.identifier, self.default_graph, self.default_union = state  # type: ignore[misc]

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    2726
    2727
    2728
    2729
    2730

    def __str__(self) -> str:
        pattern = (
            "[a rdflib:Dataset;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]"
        )
        return pattern % self.store.__class__.__name__

### `` add_graph

    add_graph(g: Optional[Union[_ContextIdentifierType, _ContextType, str]]) -> Graph

alias of graph for consistency

Source code in `rdflib/graph.py`

    2844
    2845
    2846
    2847
    2848

    def add_graph(
        self, g: Optional[Union[_ContextIdentifierType, _ContextType, str]]
    ) -> Graph:
        """alias of graph for consistency"""
        return self.graph(g)

### `` contexts

    contexts(triple: Optional[_TripleType] = None) -> Generator[_ContextType, None, None]

Source code in `rdflib/graph.py`

    2863
    2864
    2865
    2866
    2867
    2868
    2869
    2870
    2871
    2872
    2873
    2874
    2875
    2876

    def contexts(
        self, triple: Optional[_TripleType] = None
    ) -> Generator[_ContextType, None, None]:
        warnings.warn(
            "Dataset.contexts is deprecated, use Dataset.graphs instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        default = False
        for c in super(Dataset, self).contexts(triple):
            default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
            yield c
        if not default:
            yield self.graph(DATASET_DEFAULT_GRAPH_ID)

### `` graph

    graph(identifier: Optional[Union[_ContextIdentifierType, _ContextType, str]] = None, base: Optional[str] = None) -> Graph

Source code in `rdflib/graph.py`

    2753
    2754
    2755
    2756
    2757
    2758
    2759
    2760
    2761
    2762
    2763
    2764
    2765
    2766
    2767
    2768
    2769
    2770
    2771
    2772
    2773
    2774
    2775
    2776
    2777
    2778
    2779
    2780
    2781
    2782

    def graph(
        self,
        identifier: Optional[Union[_ContextIdentifierType, _ContextType, str]] = None,
        base: Optional[str] = None,
    ) -> Graph:
        if identifier is None:
            from rdflib.term import _SKOLEM_DEFAULT_AUTHORITY, rdflib_skolem_genid

            self.bind(
                "genid",
                _SKOLEM_DEFAULT_AUTHORITY + rdflib_skolem_genid,
                override=False,
            )
            identifier = BNode().skolemize()

        graph_to_copy: Optional[Graph] = None
        if isinstance(identifier, Graph) and not isinstance(
            identifier, (Dataset, ConjunctiveGraph)
        ):
            # Preserve #3259 semantics: importing an external graph through
            # Dataset.graph()/add_graph() should copy its statements.
            graph_to_copy = identifier

        g = self._graph(identifier)
        if graph_to_copy is not None:
            g.__iadd__(graph_to_copy)
        g.base = base

        self.store.add_graph(g)
        return g

### `` graphs

    graphs(triple: Optional[_TripleType] = None) -> Generator[_ContextType, None, None]

Source code in `rdflib/graph.py`

    2878
    2879
    2880
    2881
    2882
    2883
    2884
    2885
    2886

    def graphs(
        self, triple: Optional[_TripleType] = None
    ) -> Generator[_ContextType, None, None]:
        default = False
        for c in super(Dataset, self).contexts(triple):
            default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
            yield c
        if not default:
            yield self.graph(DATASET_DEFAULT_GRAPH_ID)

### `` parse

    parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Dataset

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

Parameters:

- #### `source`

  (`Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]]`, default: `None` ) –

  The source to parse. See rdflib.graph.Graph.parse for details.

- #### `publicID`

  (`Optional[str]`, default: `None` ) –

  The public ID of the source.

- #### `format`

  (`Optional[str]`, default: `None` ) –

  The format of the source.

- #### `location`

  (`Optional[str]`, default: `None` ) –

  The location of the source.

- #### `file`

  (`Optional[Union[BinaryIO, TextIO]]`, default: `None` ) –

  The file object to parse.

- #### `data`

  (`Optional[Union[str, bytes]]`, default: `None` ) –

  The data to parse.

- #### `**args`

  (`Any`, default: `{}` ) –

  Additional arguments.

Returns:

- `Dataset` –

  The graph that the source was parsed into.

Note

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

If the source is in a format that does not support named graphs its triples will be added to the default graph (i.e. :attr:`.Dataset.default_graph`). If the source is in a format that does not support named graphs its triples will be added to the default graph (i.e. Dataset.default_graph).

Caution

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

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

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

Changed in 7.0

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

Source code in `rdflib/graph.py`

    2784
    2785
    2786
    2787
    2788
    2789
    2790
    2791
    2792
    2793
    2794
    2795
    2796
    2797
    2798
    2799
    2800
    2801
    2802
    2803
    2804
    2805
    2806
    2807
    2808
    2809
    2810
    2811
    2812
    2813
    2814
    2815
    2816
    2817
    2818
    2819
    2820
    2821
    2822
    2823
    2824
    2825
    2826
    2827
    2828
    2829
    2830
    2831
    2832
    2833
    2834
    2835
    2836
    2837
    2838
    2839
    2840
    2841
    2842

    def parse(
        self,
        source: Optional[
            Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
        ] = None,
        publicID: Optional[str] = None,  # noqa: N803
        format: Optional[str] = None,
        location: Optional[str] = None,
        file: Optional[Union[BinaryIO, TextIO]] = None,
        data: Optional[Union[str, bytes]] = None,
        **args: Any,
    ) -> Dataset:
        """Parse an RDF source adding the resulting triples to the Graph.

        Args:
            source: The source to parse. See rdflib.graph.Graph.parse for details.
            publicID: The public ID of the source.
            format: The format of the source.
            location: The location of the source.
            file: The file object to parse.
            data: The data to parse.
            **args: Additional arguments.

        Returns:
            The graph that the source was parsed into.

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

        If the source is in a format that does not support named graphs its triples
        will be added to the default graph
        (i.e. :attr:`.Dataset.default_graph`).
            If the source is in a format that does not support named graphs its triples
            will be added to the default graph (i.e. Dataset.default_graph).

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

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

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

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

        ConjunctiveGraph.parse(
            self, source, publicID, format, location, file, data, **args
        )
        return self

### `` quads

    quads(quad: Optional[_TripleOrQuadPatternType] = None) -> Generator[_OptionalIdentifiedQuadType, None, None]

Source code in `rdflib/graph.py`

    2889
    2890
    2891
    2892
    2893
    2894
    2895
    2896
    2897
    2898

    def quads(  # type: ignore[override]
        self, quad: Optional[_TripleOrQuadPatternType] = None
    ) -> Generator[_OptionalIdentifiedQuadType, None, None]:
        for s, p, o, c in super(Dataset, self).quads(quad):
            # type error: Item "None" of "Optional[Graph]" has no attribute "identifier"
            if c.identifier == self.default_graph:  # type: ignore[union-attr]
                yield s, p, o, None
            else:
                # type error: Item "None" of "Optional[Graph]" has no attribute "identifier"  [union-attr]
                yield s, p, o, c.identifier  # type: ignore[union-attr]

### `` remove_graph

    remove_graph(g: Optional[Union[_ContextIdentifierType, _ContextType, str]]) -> _DatasetT

Source code in `rdflib/graph.py`

    2850
    2851
    2852
    2853
    2854
    2855
    2856
    2857
    2858
    2859
    2860
    2861

    def remove_graph(
        self: _DatasetT, g: Optional[Union[_ContextIdentifierType, _ContextType, str]]
    ) -> _DatasetT:
        if not isinstance(g, Graph):
            g = self.get_context(g)

        self.store.remove_graph(g)
        if g is None or g == self.default_graph:
            # default graph cannot be removed
            # only triples deleted, so add it back in
            self.store.add_graph(self.default_graph)
        return self

### `` serialize

    serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = None, format: str = 'trig', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) -> Union[bytes, str, Graph]

Source code in `rdflib/graph.py`

    2962
    2963
    2964
    2965
    2966
    2967
    2968
    2969
    2970
    2971
    2972

    def serialize(
        self,
        destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None,
        format: str = "trig",
        base: Optional[str] = None,
        encoding: Optional[str] = None,
        **args: Any,
    ) -> Union[bytes, str, Graph]:
        return super(Dataset, self).serialize(
            destination=destination, format=format, base=base, encoding=encoding, **args
        )

## `` Graph

    Graph(store: Union[Store, str] = 'default', identifier: Optional[Union[_ContextIdentifierType, str]] = None, namespace_manager: Optional[NamespaceManager] = None, base: Optional[str] = None, bind_namespaces: _NamespaceSetString = 'rdflib')

Bases: `Node`

An RDF Graph: a Python object containing nodes and relations between them as RDF ‘triples’.

This is the central RDFLib object class and Graph objects are almost always present in all uses of RDFLib.

Example

The basic use is to create a Graph and iterate through or query its content:

    >>> from rdflib import Graph, URIRef
    >>> g = Graph()
    >>> g.add((
    ...     URIRef("http://example.com/s1"),   # subject
    ...     URIRef("http://example.com/p1"),   # predicate
    ...     URIRef("http://example.com/o1"),   # object
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

    >>> g.add((
    ...     URIRef("http://example.com/s2"),   # subject
    ...     URIRef("http://example.com/p2"),   # predicate
    ...     URIRef("http://example.com/o2"),   # object
    ... )) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

    >>> for triple in sorted(g):  # simple looping
    ...     print(triple)
    (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))
    (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))

    >>> # get the object of the triple with subject s1 and predicate p1
    >>> o = g.value(
    ...     subject=URIRef("http://example.com/s1"),
    ...     predicate=URIRef("http://example.com/p1")
    ... )

Parameters:

- ### `store`

  (`Union[Store, str]`, default: `'default'` ) –

  The constructor accepts one argument, the “store” that will be used to store the graph data with the default being the `Memory` (in memory) Store. Other Stores that persist content to disk using various file databases or Stores that use remote servers (SPARQL systems) are supported. All builtin storetypes can be accessed via their registered names. Other Stores not shipped with RDFLib can be added as plugins, such as HDT. Registration of external plugins is described in `rdflib.plugin`.

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

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

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

  For more on Named Graphs, see the RDFLib `Dataset` class and the TriG Specification, https://www.w3.org/TR/trig/.

- ### `identifier`

  (`Optional[Union[_ContextIdentifierType, str]]`, default: `None` ) –

  identifier of the graph itself

- ### `namespace_manager`

  (`Optional[NamespaceManager]`, default: `None` ) –

  Used namespace manager. Create with bind_namespaces if `None`.

- ### `base`

  (`Optional[str]`, default: `None` ) –

  Base used for URIs

- ### `bind_namespaces`

  (`_NamespaceSetString`, default: `'rdflib'` ) –

  Used bind_namespaces for namespace_manager Is only used, when no namespace_manager is provided.

Methods:

- `__add__` –

  Set-theoretic union

- `__cmp__` –
- `__contains__` –

  Support for ‘triple in graph’ syntax.

- `__eq__` –
- `__ge__` –
- `__getitem__` –

  A graph can be “sliced” as a shortcut for the triples method

- `__gt__` –
- `__hash__` –
- `__iadd__` –

  Add all triples in Graph other to Graph.

- `__isub__` –

  Subtract all triples in Graph other from Graph.

- `__iter__` –

  Iterates over all triples in the store.

- `__le__` –
- `__len__` –

  Returns the number of triples in the graph.

- `__lt__` –
- `__mul__` –

  Set-theoretic intersection.

- `__reduce__` –
- `__repr__` –
- `__str__` –
- `__sub__` –

  Set-theoretic difference.

- `__xor__` –

  Set-theoretic XOR.

- `absolutize` –

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

- `add` –

  Add a triple with self as context.

- `addN` –

  Add a sequence of triple with context

- `all_nodes` –
- `bind` –

  Bind prefix to namespace

- `cbd` –

  Retrieves the Concise Bounded Description of a Resource from a Graph.

- `close` –

  Close the graph store

- `collection` –

  Create a new `Collection` instance.

- `commit` –

  Commits active transactions

- `compute_qname` –
- `connected` –

  Check if the Graph is connected.

- `de_skolemize` –
- `destroy` –

  Destroy the store identified by `configuration` if supported

- `isomorphic` –

  Check if this graph is isomorphic to another graph.

- `items` –

  Generator over all items in the resource specified by list

- `n3` –

  Return an n3 identifier for the Graph

- `namespaces` –

  Generator over all the prefix, namespace tuples

- `objects` –

  A generator of (optionally unique) objects with the given

- `open` –

  Open the graph store

- `parse` –

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

- `predicate_objects` –

  A generator of (optionally unique) (predicate, object) tuples

- `predicates` –

  Generate predicates with the given subject and object.

- `print` –
- `qname` –
- `query` –

  Query this graph.

- `remove` –

  Remove a triple from the graph

- `resource` –

  Create a new `Resource` instance.

- `rollback` –

  Rollback active transactions

- `serialize` –

  Serialize the graph.

- `set` –

  Convenience method to update the value of object

- `skolemize` –
- `subject_objects` –

  A generator of (optionally unique) (subject, object) tuples

- `subject_predicates` –

  A generator of (optionally unique) (subject, predicate) tuples

- `subjects` –

  A generator of (optionally unique) subjects with the given

- `toPython` –
- `transitiveClosure` –

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

- `transitive_objects` –

  Transitively generate objects for the `predicate` relationship

- `transitive_subjects` –

  Transitively generate subjects for the `predicate` relationship

- `triples` –

  Generator over the triple store.

- `triples_choices` –
- `update` –

  Update this graph with the given update query.

- `value` –

  Get a value for a pair of two criteria

Attributes:

- `__and__` –
- `__or__` –
- `base` (`Optional[str]`) –
- `context_aware` (`bool`) –
- `default_union` (`bool`) –
- `formula_aware` (`bool`) –
- `identifier` (`_ContextIdentifierType`) –
- `namespace_manager` (`NamespaceManager`) –

  this graph’s namespace-manager

- `store` (`Store`) –

Source code in `rdflib/graph.py`

    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544

    def __init__(
        self,
        store: Union[Store, str] = "default",
        identifier: Optional[Union[_ContextIdentifierType, str]] = None,
        namespace_manager: Optional[NamespaceManager] = None,
        base: Optional[str] = None,
        bind_namespaces: _NamespaceSetString = "rdflib",
    ):
        super(Graph, self).__init__()
        self.base = base
        self.__identifier: _ContextIdentifierType
        self.__identifier = identifier or BNode()  # type: ignore[assignment]
        if not isinstance(self.__identifier, IdentifiedNode):
            self.__identifier = URIRef(self.__identifier)  # type: ignore[unreachable]
        self.__store: Store
        if not isinstance(store, Store):
            # TODO: error handling
            self.__store = store = plugin.get(store, Store)()
        else:
            self.__store = store
        self.__namespace_manager = namespace_manager
        self._bind_namespaces = bind_namespaces
        self.context_aware = False
        self.formula_aware = False
        self.default_union = False

### `` __and__ `class-attribute` `instance-attribute`

    __and__ = __mul__

### `` __identifier `instance-attribute`

    __identifier: _ContextIdentifierType = identifier or BNode()

### `` __namespace_manager `instance-attribute`

    __namespace_manager = namespace_manager

### `` __or__ `class-attribute` `instance-attribute`

    __or__ = __add__

### `` __store `instance-attribute`

    __store: Store

### `` base `instance-attribute`

    base: Optional[str] = base

### `` context_aware `instance-attribute`

    context_aware: bool = False

### `` default_union `instance-attribute`

    default_union: bool = False

### `` formula_aware `instance-attribute`

    formula_aware: bool = False

### `` identifier `property`

    identifier: _ContextIdentifierType

### `` namespace_manager `property` `writable`

    namespace_manager: NamespaceManager

this graph’s namespace-manager

### `` store `property`

    store: Store

### `` __add__

    __add__(other: Graph) -> Graph

Set-theoretic union BNode IDs are not changed.

Source code in `rdflib/graph.py`

    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864

    def __add__(self, other: Graph) -> Graph:
        """Set-theoretic union
        BNode IDs are not changed."""
        try:
            retval = type(self)()
        except TypeError:
            retval = Graph()
        for prefix, uri in set(list(self.namespaces()) + list(other.namespaces())):
            retval.bind(prefix, uri)
        for x in self:
            retval.add(x)
        for y in other:
            retval.add(y)
        return retval

### `` __cmp__

    __cmp__(other) -> int

Source code in `rdflib/graph.py`

    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817

    def __cmp__(self, other) -> int:
        if other is None:
            return -1
        elif isinstance(other, Graph):
            return (self.identifier > other.identifier) - (
                self.identifier < other.identifier
            )
        else:
            # Note if None is considered equivalent to owl:Nothing
            # Then perhaps a graph with length 0 should be considered
            # equivalent to None (if compared to it)?
            return 1

### `` __contains__

    __contains__(triple: _TripleSelectorType) -> bool

Support for ‘triple in graph’ syntax.

Parameters:

- #### `triple`

  (`_TripleSelectorType`) –

  The triple pattern to check for.

Returns:

- `bool` –

  True if the triple pattern exists in the graph, False otherwise.

Source code in `rdflib/graph.py`

    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801

    def __contains__(self, triple: _TripleSelectorType) -> bool:
        """Support for 'triple in graph' syntax.

        Args:
            triple: The triple pattern to check for.

        Returns:
            True if the triple pattern exists in the graph, False otherwise.
        """
        for triple in self.triples(triple):
            return True
        return False

### `` __eq__

    __eq__(other) -> bool

Source code in `rdflib/graph.py`

    819
    820

    def __eq__(self, other) -> bool:
        return isinstance(other, Graph) and self.identifier == other.identifier

### `` __ge__

    __ge__(other: Graph) -> bool

Source code in `rdflib/graph.py`

    835
    836

    def __ge__(self, other: Graph) -> bool:
        return self > other or self == other

### `` __getitem__

    __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"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

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

    >>> list(g[:namespace.RDFS.label]) # all label triples
    [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]

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

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

- Name of all Bobs friends: `g[bob : FOAF.knows/FOAF.name ]`
- Some label for Bob: `g[bob : DC.title|FOAF.name|RDFS.label]`
- All friends and friends of friends of Bob: `g[bob : FOAF.knows * "+"]`
- etc.

New in version 4.0

Source code in `rdflib/graph.py`

    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768

    def __getitem__(self, 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

        ```python
        >>> import rdflib
        >>> g = rdflib.Graph()
        >>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>

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

        >>> list(g[:namespace.RDFS.label]) # all label triples
        [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]

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

        ```

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

        - Name of all Bobs friends: `g[bob : FOAF.knows/FOAF.name ]`
        - Some label for Bob: `g[bob : DC.title|FOAF.name|RDFS.label]`
        - All friends and friends of friends of Bob: `g[bob : FOAF.knows * "+"]`
        - etc.

        !!! example "New in version 4.0"
        """

        if isinstance(item, slice):
            s, p, o = item.start, item.stop, item.step
            if s is None and p is None and o is None:
                return self.triples((s, p, o))
            elif s is None and p is None:
                # type error: Argument 1 to "subject_predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
                return self.subject_predicates(o)  # type: ignore[arg-type]
            elif s is None and o is None:
                # type error: Argument 1 to "subject_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
                return self.subject_objects(p)  # type: ignore[arg-type]
            elif p is None and o is None:
                # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
                return self.predicate_objects(s)  # type: ignore[arg-type]
            elif s is None:
                # type error: Argument 1 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
                # Argument 2 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]"
                return self.subjects(p, o)  # type: ignore[arg-type]
            elif p is None:
                # type error: Argument 1 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
                # Argument 2 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
                return self.predicates(s, o)  # type: ignore[arg-type]
            elif o is None:
                # type error: Argument 1 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]"
                # Argument 2 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
                return self.objects(s, p)  # type: ignore[arg-type]
            else:
                # type error: Unsupported operand types for in ("Tuple[Union[int, Any], Union[int, Any], Union[int, Any]]" and "Graph")
                # all given
                return (s, p, o) in self  # type: ignore[operator]

        elif isinstance(item, (Path, Node)):
            # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[Path, Node]"; expected "Optional[Node]"
            return self.predicate_objects(item)  # type: ignore[arg-type]

        else:
            raise TypeError(
                "You can only index a graph by a single rdflib term or path, or a slice of rdflib terms."
            )

### `` __gt__

    __gt__(other) -> bool

Source code in `rdflib/graph.py`

    830
    831
    832
    833

    def __gt__(self, other) -> bool:
        return (isinstance(other, Graph) and self.identifier > other.identifier) or (
            other is not None
        )

### `` __hash__

    __hash__() -> int

Source code in `rdflib/graph.py`

    803
    804

    def __hash__(self) -> int:
        return hash(self.identifier)

### `` __iadd__

    __iadd__(other: Iterable[_TripleType]) -> _GraphT

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

Source code in `rdflib/graph.py`

    838
    839
    840
    841
    842

    def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT:
        """Add all triples in Graph other to Graph.
        BNode IDs are not changed."""
        self.addN((s, p, o, self) for s, p, o in other)
        return self

### `` __isub__

    __isub__(other: Iterable[_TripleType]) -> _GraphT

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

Source code in `rdflib/graph.py`

    844
    845
    846
    847
    848
    849

    def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT:
        """Subtract all triples in Graph other from Graph.
        BNode IDs are not changed."""
        for triple in other:
            self.remove(triple)
        return self

### `` __iter__

    __iter__() -> Generator[_TripleType, None, None]

Iterates over all triples in the store.

Returns:

- `None` –

  A generator yielding all triples in the store.

Source code in `rdflib/graph.py`

    782
    783
    784
    785
    786
    787
    788

    def __iter__(self) -> Generator[_TripleType, None, None]:
        """Iterates over all triples in the store.

        Returns:
            A generator yielding all triples in the store.
        """
        return self.triples((None, None, None))

### `` __le__

    __le__(other: Graph) -> bool

Source code in `rdflib/graph.py`

    827
    828

    def __le__(self, other: Graph) -> bool:
        return self < other or self == other

### `` __len__

    __len__() -> int

Returns the number of triples in the graph.

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

Returns:

- `int` –

  The number of triples in the graph.

Source code in `rdflib/graph.py`

    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780

    def __len__(self) -> int:
        """Returns the number of triples in the graph.

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

        Returns:
            The number of triples in the graph.
        """
        # type error: Unexpected keyword argument "context" for "__len__" of "Store"
        return self.__store.__len__(context=self)  # type: ignore[call-arg]

### `` __lt__

    __lt__(other) -> bool

Source code in `rdflib/graph.py`

    822
    823
    824
    825

    def __lt__(self, other) -> bool:
        return (other is None) or (
            isinstance(other, Graph) and self.identifier < other.identifier
        )

### `` __mul__

    __mul__(other: Graph) -> Graph

Set-theoretic intersection. BNode IDs are not changed.

Source code in `rdflib/graph.py`

    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876

    def __mul__(self, other: Graph) -> Graph:
        """Set-theoretic intersection.
        BNode IDs are not changed."""
        try:
            retval = type(self)()
        except TypeError:
            retval = Graph()
        for x in other:
            if x in self:
                retval.add(x)
        return retval

### `` __reduce__

    __reduce__() -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]

Source code in `rdflib/graph.py`

    1806
    1807
    1808
    1809
    1810
    1811
    1812
    1813

    def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
        return (
            Graph,
            (
                self.store,
                self.identifier,
            ),
        )

### `` __repr__

    __repr__() -> str

Source code in `rdflib/graph.py`

    567
    568

    def __repr__(self) -> str:
        return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    570
    571
    572
    573
    574
    575
    576
    577
    578

    def __str__(self) -> str:
        if isinstance(self.identifier, URIRef):
            return (
                "%s a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']."
            ) % (self.identifier.n3(), self.store.__class__.__name__)
        else:
            return (
                "[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]."
            ) % self.store.__class__.__name__

### `` __sub__

    __sub__(other: Graph) -> Graph

Set-theoretic difference. BNode IDs are not changed.

Source code in `rdflib/graph.py`

    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888

    def __sub__(self, other: Graph) -> Graph:
        """Set-theoretic difference.
        BNode IDs are not changed."""
        try:
            retval = type(self)()
        except TypeError:
            retval = Graph()
        for x in self:
            if x not in other:
                retval.add(x)
        return retval

### `` __xor__

    __xor__(other: Graph) -> Graph

Set-theoretic XOR. BNode IDs are not changed.

Source code in `rdflib/graph.py`

    890
    891
    892
    893

    def __xor__(self, other: Graph) -> Graph:
        """Set-theoretic XOR.
        BNode IDs are not changed."""
        return (self - other) + (other - self)

### `` absolutize

    absolutize(uri: str, defrag: int = 1) -> URIRef

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

Source code in `rdflib/graph.py`

    1388
    1389
    1390

    def absolutize(self, uri: str, defrag: int = 1) -> URIRef:
        """Turn uri into an absolute URI if it's not one already"""
        return self.namespace_manager.absolutize(uri, defrag)

### `` add

    add(triple: _TripleType) -> _GraphT

Add a triple with self as context.

Parameters:

- #### `triple`

  (`_TripleType`) –

  The triple to add to the graph.

Returns:

- `_GraphT` –

  The graph instance.

Source code in `rdflib/graph.py`

    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631

    def add(self: _GraphT, triple: _TripleType) -> _GraphT:
        """Add a triple with self as context.

        Args:
            triple: The triple to add to the graph.

        Returns:
            The graph instance.
        """
        s, p, o = triple
        assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,)
        assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,)
        assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,)
        self.__store.add((s, p, o), self, quoted=False)
        return self

### `` addN

    addN(quads: Iterable[_QuadType]) -> _GraphT

Add a sequence of triple with context

Source code in `rdflib/graph.py`

    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643

    def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT:  # noqa: N802
        """Add a sequence of triple with context"""

        self.__store.addN(
            (s, p, o, c)
            for s, p, o, c in quads
            if isinstance(c, Graph)
            and c.identifier is self.identifier
            and _assertnode(s, p, o)
        )
        return self

### `` all_nodes

    all_nodes() -> Set[Node]

Source code in `rdflib/graph.py`

    1886
    1887
    1888
    1889

    def all_nodes(self) -> Set[Node]:
        res = set(self.objects())
        res.update(self.subjects())
        return res

### `` bind

    bind(prefix: Optional[str], namespace: Any, override: bool = True, replace: bool = False) -> None

Bind prefix to namespace

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

if replace, replace any existing prefix with the new namespace

Parameters:

- #### `prefix`

  (`Optional[str]`) –

  The prefix to bind

- #### `namespace`

  (`Any`) –

  The namespace to bind the prefix to

- #### `override`

  (`bool`, default: `True` ) –

  If True, override any existing prefix binding

- #### `replace`

  (`bool`, default: `False` ) –

  If True, replace any existing namespace binding

Example

    graph.bind("foaf", "http://xmlns.com/foaf/0.1/")

Source code in `rdflib/graph.py`

    1343
    1344
    1345
    1346
    1347
    1348
    1349
    1350
    1351
    1352
    1353
    1354
    1355
    1356
    1357
    1358
    1359
    1360
    1361
    1362
    1363
    1364
    1365
    1366
    1367
    1368
    1369
    1370
    1371
    1372
    1373
    1374
    1375
    1376
    1377

    def bind(
        self,
        prefix: Optional[str],
        namespace: Any,  # noqa: F811
        override: bool = True,
        replace: bool = False,
    ) -> None:
        """Bind prefix to namespace

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

        if replace, replace any existing prefix with the new namespace

        Args:
            prefix: The prefix to bind
            namespace: The namespace to bind the prefix to
            override: If True, override any existing prefix binding
            replace: If True, replace any existing namespace binding

        Example:
            ```python
            graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
            ```
        """
        # TODO FIXME: This method's behaviour should be simplified and made
        # more robust. If the method cannot do what it is asked it should raise
        # an exception, it is also unclear why this method has all the
        # different modes. It seems to just make it more complex to use, maybe
        # it should be clarified when someone will need to use override=False
        # and replace=False. And also why silent failure here is preferred over
        # raising an exception.
        return self.namespace_manager.bind(
            prefix, namespace, override=override, replace=replace
        )

### `` cbd

    cbd(resource: _SubjectType, *, target_graph: Graph | None = None, include_reifications: bool = True) -> Graph

Retrieves the Concise Bounded Description of a Resource from a Graph.

Parameters:

- #### `resource`

  (`_SubjectType`) –

  A URIRef object, the Resource to query for.

- #### `target_graph`

  (`Graph | None`, default: `None` ) –

  Optionally, a graph to add the CBD to; otherwise, a new graph is created for the CBD.

- #### `include_reifications`

  (`bool`, default: `True` ) –

  If False, skip Rule 3 to exclude reified statements (default: True)

Returns:

- `Graph` –

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

Note

Concise Bounded Description (CBD) is defined as:

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

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

2. Recursively, for all statements identified in the subgraph thus far having a blank node object, include in the subgraph all statements in the source graph where the subject of the statement is the blank node in question and which are not already included in the subgraph.

3. Recursively, for all statements included in the subgraph thus far, for all reifications of each statement in the source graph, include the concise bounded description beginning from the rdf:Statement node of each reification.

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

If include_reifications is set to False, Rule 3 above will be skipped, meaning reified statements will not be included in the CBD. This can improve performance when reified statements are not present or can be used to deliberately exclude them from the result.

Source code in `rdflib/graph.py`

    2025
    2026
    2027
    2028
    2029
    2030
    2031
    2032
    2033
    2034
    2035
    2036
    2037
    2038
    2039
    2040
    2041
    2042
    2043
    2044
    2045
    2046
    2047
    2048
    2049
    2050
    2051
    2052
    2053
    2054
    2055
    2056
    2057
    2058
    2059
    2060
    2061
    2062
    2063
    2064
    2065
    2066
    2067
    2068
    2069
    2070
    2071
    2072
    2073
    2074
    2075
    2076
    2077
    2078
    2079
    2080
    2081
    2082
    2083
    2084
    2085
    2086
    2087
    2088
    2089
    2090
    2091
    2092
    2093
    2094
    2095
    2096
    2097
    2098
    2099
    2100
    2101
    2102
    2103
    2104
    2105
    2106
    2107
    2108
    2109
    2110

    def cbd(
        self,
        resource: _SubjectType,
        *,
        target_graph: Graph | None = None,
        include_reifications: bool = True,
    ) -> Graph:
        """Retrieves the Concise Bounded Description of a Resource from a Graph.

        Args:
            resource: A URIRef object, the Resource to query for.
            target_graph: Optionally, a graph to add the CBD to; otherwise,
                a new graph is created for the CBD.
            include_reifications: If False, skip Rule 3 to exclude reified statements (default: True)

        Returns:
            A Graph, subgraph of self if no graph was provided otherwise the provided graph.

        Note:
            Concise Bounded Description (CBD) is defined as:

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

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

            2. Recursively, for all statements identified in the subgraph thus far having a blank
                node object, include in the subgraph all statements in the source graph where the
                subject of the statement is the blank node in question and which are not already
                included in the subgraph.

            3. Recursively, for all statements included in the subgraph thus far, for all
                reifications of each statement in the source graph, include the concise bounded
                description beginning from the rdf:Statement node of each reification.

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

            If include_reifications is set to False, Rule 3 above will be skipped, meaning reified statements
            will not be included in the CBD. This can improve performance when reified statements are not present
            or can be used to deliberately exclude them from the result.
        """
        # If no target graph is provided, create a new Graph to hold the CBD.
        if target_graph is None:
            subgraph = Graph()
        else:
            subgraph = target_graph

        def add_to_cbd(uri: _SubjectType) -> None:
            # Rule 3 Preparation:
            # If reifications are to be included, build an index mapping triples with
            # this subject to the set of reification nodes (rdf:Statement nodes) that reify them.
            if include_reifications:
                reif_index: dict[_TripleType, set[_SubjectType]] = {}
                for stmt in self.subjects(RDF.subject, uri):
                    p: _PredicateType = self.value(stmt, RDF.predicate)  # type: ignore[assignment]
                    o = self.value(stmt, RDF.object)
                    if p is not None and o is not None:
                        triple = (uri, p, o)
                        if triple not in reif_index:
                            reif_index[triple] = {stmt}
                        else:
                            reif_index[triple].add(stmt)

            # For all triples where the subject is the current subject (Rule 1)
            for s, p, o in self.triples((uri, None, None)):
                # Add the triple to the CBD subgraph
                subgraph.add((s, p, o))
                # If the object is a blank node, recursively add its CBD (Rule 2)
                if type(o) is BNode and (o, None, None) not in subgraph:
                    add_to_cbd(o)

                # If including reifications (Rule 3):
                if include_reifications:
                    # For each reification node of this triple, recursively add its CBD
                    stmts = reif_index.get((s, p, o), set())
                    for stmt in stmts:
                        if (stmt, None, None) not in subgraph:
                            add_to_cbd(stmt)

        # Start the CBD construction from the given resource
        add_to_cbd(resource)

        return subgraph

### `` close

    close(commit_pending_transaction: bool = False) -> None

Close the graph store

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

Source code in `rdflib/graph.py`

    609
    610
    611
    612
    613
    614
    615

    def close(self, commit_pending_transaction: bool = False) -> None:
        """Close the graph store

        Might be necessary for stores that require closing a connection to a
        database or releasing some resource.
        """
        return self.__store.close(commit_pending_transaction=commit_pending_transaction)

### `` collection

    collection(identifier: _SubjectType) -> Collection

Create a new `Collection` instance.

Parameters:

- #### `identifier`

  (`_SubjectType`) –

  A URIRef or BNode instance.

Returns:

- `Collection` –

  A new Collection 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) ]

Source code in `rdflib/graph.py`

    1891
    1892
    1893
    1894
    1895
    1896
    1897
    1898
    1899
    1900
    1901
    1902
    1903
    1904
    1905
    1906
    1907
    1908
    1909
    1910
    1911
    1912
    1913

    def collection(self, identifier: _SubjectType) -> Collection:
        """Create a new `Collection` instance.

        Args:
            identifier: A URIRef or BNode instance.

        Returns:
            A new Collection instance.

        Example:
            ```python
            >>> 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) ]

            ```
        """

        return Collection(self, identifier)

### `` commit

    commit() -> _GraphT

Commits active transactions

Source code in `rdflib/graph.py`

    589
    590
    591
    592

    def commit(self: _GraphT) -> _GraphT:
        """Commits active transactions"""
        self.__store.commit()
        return self

### `` compute_qname

    compute_qname(uri: str, generate: bool = True) -> Tuple[str, URIRef, str]

Source code in `rdflib/graph.py`

    1340
    1341

    def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
        return self.namespace_manager.compute_qname(uri, generate)

### `` connected

    connected() -> bool

Check if the Graph is connected.

The Graph is considered undirectional.

Returns:

- `bool` –

  True if all nodes have been visited and there are no unvisited nodes left,

- `bool` –

  False otherwise.

Note

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.

Source code in `rdflib/graph.py`

    1845
    1846
    1847
    1848
    1849
    1850
    1851
    1852
    1853
    1854
    1855
    1856
    1857
    1858
    1859
    1860
    1861
    1862
    1863
    1864
    1865
    1866
    1867
    1868
    1869
    1870
    1871
    1872
    1873
    1874
    1875
    1876
    1877
    1878
    1879
    1880
    1881
    1882
    1883
    1884

    def connected(self) -> bool:
        """Check if the Graph is connected.

        The Graph is considered undirectional.

        Returns:
            True if all nodes have been visited and there are no unvisited nodes left,
            False otherwise.

        Note:
            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.
        """
        all_nodes = list(self.all_nodes())
        discovered = []

        # take a random one, could also always take the first one, doesn't
        # really matter.
        if not all_nodes:
            return False

        visiting = [all_nodes[random.randrange(len(all_nodes))]]
        while visiting:
            x = visiting.pop()
            if x not in discovered:
                discovered.append(x)
            for new_x in self.objects(subject=x):
                if new_x not in discovered and new_x not in visiting:
                    visiting.append(new_x)
            for new_x in self.subjects(object=x):
                if new_x not in discovered and new_x not in visiting:
                    visiting.append(new_x)

        # optimisation by only considering length, since no new objects can
        # be introduced anywhere.
        if len(all_nodes) == len(discovered):
            return True
        else:
            return False

### `` de_skolemize

    de_skolemize(new_graph: Optional[Graph] = None, uriref: Optional[URIRef] = None) -> Graph

Source code in `rdflib/graph.py`

    1982
    1983
    1984
    1985
    1986
    1987
    1988
    1989
    1990
    1991
    1992
    1993
    1994
    1995
    1996
    1997
    1998
    1999
    2000
    2001
    2002
    2003
    2004
    2005
    2006
    2007
    2008
    2009
    2010
    2011
    2012
    2013
    2014
    2015
    2016
    2017
    2018
    2019
    2020
    2021
    2022
    2023

    def de_skolemize(
        self, new_graph: Optional[Graph] = None, uriref: Optional[URIRef] = None
    ) -> Graph:
        def do_de_skolemize(uriref: URIRef, t: _TripleType) -> _TripleType:
            (s, p, o) = t
            if s == uriref:
                if TYPE_CHECKING:
                    assert isinstance(s, URIRef)
                s = s.de_skolemize()
            if o == uriref:
                if TYPE_CHECKING:
                    assert isinstance(o, URIRef)
                o = o.de_skolemize()
            return s, p, o

        def do_de_skolemize2(t: _TripleType) -> _TripleType:
            (s, p, o) = t

            if RDFLibGenid._is_rdflib_skolem(s):
                # type error: Argument 1 to "RDFLibGenid" has incompatible type "Node"; expected "str"
                s = RDFLibGenid(s).de_skolemize()  # type: ignore[arg-type]
            elif Genid._is_external_skolem(s):
                # type error: Argument 1 to "Genid" has incompatible type "Node"; expected "str"
                s = Genid(s).de_skolemize()  # type: ignore[arg-type]

            if isinstance(o, URIRef):
                if RDFLibGenid._is_rdflib_skolem(o):
                    o = RDFLibGenid(o).de_skolemize()
                elif Genid._is_external_skolem(o):
                    o = Genid(o).de_skolemize()

            return s, p, o

        retval = Graph() if new_graph is None else new_graph

        if uriref is None:
            self._process_skolem_tuples(retval, do_de_skolemize2)
        elif isinstance(uriref, Genid):
            # type error: Argument 1 to "do_de_skolemize" has incompatible type "Optional[URIRef]"; expected "URIRef"
            self._process_skolem_tuples(retval, lambda t: do_de_skolemize(uriref, t))  # type: ignore[arg-type, unused-ignore]

        return retval

### `` destroy

    destroy(configuration: str) -> _GraphT

Destroy the store identified by `configuration` if supported

Source code in `rdflib/graph.py`

    583
    584
    585
    586

    def destroy(self: _GraphT, configuration: str) -> _GraphT:
        """Destroy the store identified by `configuration` if supported"""
        self.__store.destroy(configuration)
        return self

### `` isomorphic

    isomorphic(other: Graph) -> bool

Check if this graph is isomorphic to another graph.

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

Parameters:

- #### `other`

  (`Graph`) –

  The graph to compare with.

Returns:

- `bool` –

  True if the graphs are isomorphic, False otherwise.

Note

This is only an approximation. See rdflib.compare for a correct implementation of isomorphism checks.

Source code in `rdflib/graph.py`

    1815
    1816
    1817
    1818
    1819
    1820
    1821
    1822
    1823
    1824
    1825
    1826
    1827
    1828
    1829
    1830
    1831
    1832
    1833
    1834
    1835
    1836
    1837
    1838
    1839
    1840
    1841
    1842
    1843

    def isomorphic(self, other: Graph) -> bool:
        """Check if this graph is isomorphic to another graph.

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

        Args:
            other: The graph to compare with.

        Returns:
            True if the graphs are isomorphic, False otherwise.

        Note:
            This is only an approximation. See rdflib.compare for a correct
            implementation of isomorphism checks.
        """
        # TODO: this is only an approximation.
        if len(self) != len(other):
            return False
        for s, p, o in self:
            if not isinstance(s, BNode) and not isinstance(o, BNode):
                if not (s, p, o) in other:  # noqa: E713
                    return False
        for s, p, o in other:
            if not isinstance(s, BNode) and not isinstance(o, BNode):
                if not (s, p, o) in self:  # noqa: E713
                    return False
        # TODO: very well could be a false positive at this point yet.
        return True

### `` items

    items(list: Node) -> Generator[Node, None, None]

Generator over all items in the resource specified by list

Parameters:

- #### `list`

  (`Node`) –

  An RDF collection.

Source code in `rdflib/graph.py`

    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223

    def items(self, list: Node) -> Generator[Node, None, None]:
        """Generator over all items in the resource specified by list

        Args:
            list: An RDF collection.
        """
        chain = set([list])
        while list:
            item = self.value(list, RDF.first)
            if item is not None:
                yield item
            # type error: Incompatible types in assignment (expression has type "Optional[Node]", variable has type "Node")
            list = self.value(list, RDF.rest)  # type: ignore[assignment]
            if list in chain:
                raise ValueError("List contains a recursive rdf:rest reference")
            chain.add(list)

### `` n3

    n3(namespace_manager: Optional[NamespaceManager] = None) -> str

Return an n3 identifier for the Graph

Source code in `rdflib/graph.py`

    1802
    1803
    1804

    def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str:
        """Return an n3 identifier for the Graph"""
        return "[%s]" % self.identifier.n3(namespace_manager=namespace_manager)

### `` namespaces

    namespaces() -> Generator[Tuple[str, URIRef], None, None]

Generator over all the prefix, namespace tuples

Returns:

- `None` –

  Generator yielding prefix, namespace tuples

Source code in `rdflib/graph.py`

    1379
    1380
    1381
    1382
    1383
    1384
    1385
    1386

    def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]:
        """Generator over all the prefix, namespace tuples

        Returns:
            Generator yielding prefix, namespace tuples
        """
        for prefix, namespace in self.namespace_manager.namespaces():  # noqa: F402
            yield prefix, namespace

### `` objects

    objects(subject: Optional[Union[_SubjectType, List[_SubjectType]]] = None, predicate: Union[None, Path, _PredicateType] = None, unique: bool = False) -> Generator[_ObjectType, None, None]

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

Parameters:

- #### `subject`

  (`Optional[Union[_SubjectType, List[_SubjectType]]]`, default: `None` ) –

  A specific subject or a list of subjects to match or None to match any subject.

- #### `predicate`

  (`Union[None, Path, _PredicateType]`, default: `None` ) –

  A specific predicate to match or None to match any predicate.

- #### `unique`

  (`bool`, default: `False` ) –

  If True, only yield unique objects.

Yields:

- `_ObjectType` –

  Objects matching the given subject and predicate.

Source code in `rdflib/graph.py`

     987
     988
     989
     990
     991
     992
     993
     994
     995
     996
     997
     998
     999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023

    def objects(
        self,
        subject: Optional[Union[_SubjectType, List[_SubjectType]]] = None,
        predicate: Union[None, Path, _PredicateType] = None,
        unique: bool = False,
    ) -> Generator[_ObjectType, None, None]:
        """A generator of (optionally unique) objects with the given
        subject(s) and predicate

        Args:
            subject: A specific subject or a list of subjects to match or None to match any subject.
            predicate: A specific predicate to match or None to match any predicate.
            unique: If True, only yield unique objects.

        Yields:
            Objects matching the given subject and predicate.
        """
        if isinstance(subject, list):
            for subj in subject:
                for o in self.objects(subj, predicate, unique):
                    yield o
        else:
            if not unique:
                for s, p, o in self.triples((subject, predicate, None)):
                    yield o
            else:
                objs = set()
                for s, p, o in self.triples((subject, predicate, None)):
                    if o not in objs:
                        yield o
                        try:
                            objs.add(o)
                        except MemoryError as e:
                            logger.error(
                                f"{e}. Consider not setting parameter 'unique' to True"
                            )
                            raise

### `` open

    open(configuration: Union[str, tuple[str, str]], create: bool = False) -> Optional[int]

Open the graph store

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

Source code in `rdflib/graph.py`

    599
    600
    601
    602
    603
    604
    605
    606
    607

    def open(
        self, configuration: Union[str, tuple[str, str]], create: bool = False
    ) -> Optional[int]:
        """Open the graph store

        Might be necessary for stores that require opening a connection to a
        database or acquiring some resource.
        """
        return self.__store.open(configuration, create)

### `` parse

    parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]] = None, publicID: Optional[str] = None, format: Optional[str] = None, location: Optional[str] = None, file: Optional[Union[BinaryIO, TextIO]] = None, data: Optional[Union[str, bytes]] = None, **args: Any) -> Graph

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

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

Parameters:

- #### `source`

  (`Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]]`, default: `None` ) –

  An `xml.sax.xmlreader.InputSource`, file-like object, `pathlib.Path` like object, or string. In the case of a string the string is the location of the source.

- #### `publicID`

  (`Optional[str]`, default: `None` ) –

  The logical URI to use as the document base. If None specified the document location is used (at least in the case where there is a document location). This is used as the base URI when resolving relative URIs in the source document, as defined in `IETF RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-5.1.4>`_, given the source document does not define a base URI.

- #### `format`

  (`Optional[str]`, default: `None` ) –

  Used if format can not be determined from source, e.g. file extension or Media Type. Format support is managed with plugins. Available formats are e.g. “turle”, “xml”, “n3”, “nt” and “trix” or see parser module.

- #### `location`

  (`Optional[str]`, default: `None` ) –

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

- #### `file`

  (`Optional[Union[BinaryIO, TextIO]]`, default: `None` ) –

  A file-like object.

- #### `data`

  (`Optional[Union[str, bytes]]`, default: `None` ) –

  A string containing the data to be parsed.

- #### `args`

  (`Any`, default: `{}` ) –

  Additional arguments to pass to the parser.

Returns:

- `Graph` –

  self, i.e. the Graph instance.

Example

    >>> my_data = '''
    ... <rdf:RDF
    ...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    ...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    ... >
    ...   <rdf:Description>
    ...     <rdfs:label>Example</rdfs:label>
    ...     <rdfs:comment>This is really just an example.</rdfs:comment>
    ...   </rdf:Description>
    ... </rdf:RDF>
    ... '''
    >>> import os, tempfile
    >>> fd, file_name = tempfile.mkstemp()
    >>> f = os.fdopen(fd, "w")
    >>> dummy = f.write(my_data)  # Returns num bytes written
    >>> f.close()

    >>> g = Graph()
    >>> result = g.parse(data=my_data, format="application/rdf+xml")
    >>> len(g)
    2

    >>> g = Graph()
    >>> result = g.parse(location=file_name, format="application/rdf+xml")
    >>> len(g)
    2

    >>> g = Graph()
    >>> with open(file_name, "r") as f:
    ...     result = g.parse(f, format="application/rdf+xml")
    >>> len(g)
    2

    >>> os.remove(file_name)

    >>> # default turtle parsing
    >>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
    >>> len(g)
    3

Caution

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

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

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

Source code in `rdflib/graph.py`

    1527
    1528
    1529
    1530
    1531
    1532
    1533
    1534
    1535
    1536
    1537
    1538
    1539
    1540
    1541
    1542
    1543
    1544
    1545
    1546
    1547
    1548
    1549
    1550
    1551
    1552
    1553
    1554
    1555
    1556
    1557
    1558
    1559
    1560
    1561
    1562
    1563
    1564
    1565
    1566
    1567
    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577
    1578
    1579
    1580
    1581
    1582
    1583
    1584
    1585
    1586
    1587
    1588
    1589
    1590
    1591
    1592
    1593
    1594
    1595
    1596
    1597
    1598
    1599
    1600
    1601
    1602
    1603
    1604
    1605
    1606
    1607
    1608
    1609
    1610
    1611
    1612
    1613
    1614
    1615
    1616
    1617
    1618
    1619
    1620
    1621
    1622
    1623
    1624
    1625
    1626
    1627
    1628
    1629
    1630
    1631
    1632
    1633
    1634
    1635
    1636
    1637
    1638
    1639
    1640
    1641
    1642
    1643
    1644
    1645
    1646
    1647
    1648
    1649
    1650
    1651
    1652
    1653
    1654
    1655
    1656
    1657
    1658
    1659
    1660
    1661
    1662
    1663
    1664
    1665
    1666
    1667
    1668
    1669
    1670
    1671
    1672
    1673

    def parse(
        self,
        source: Optional[
            Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
        ] = None,
        publicID: Optional[str] = None,  # noqa: N803
        format: Optional[str] = None,
        location: Optional[str] = None,
        file: Optional[Union[BinaryIO, TextIO]] = None,
        data: Optional[Union[str, bytes]] = None,
        **args: Any,
    ) -> Graph:
        """Parse an RDF source adding the resulting triples to the Graph.

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

        Args:
            source: An `xml.sax.xmlreader.InputSource`, file-like object,
                `pathlib.Path` like object, or string. In the case of a string the string
                is the location of the source.
            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). This is used as the base URI when
                resolving relative URIs in the source document, as defined in `IETF
                RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-5.1.4>`_,
                given the source document does not define a base URI.
            format: Used if format can not be determined from source, e.g.
                file extension or Media Type. Format support is managed
                with [plugins][rdflib.plugin].
                Available formats are e.g. "turle", "xml", "n3", "nt" and "trix"
                or see [parser module][rdflib.plugins.parsers].
            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.
            args: Additional arguments to pass to the parser.

        Returns:
            self, i.e. the Graph instance.

        Example:
            ```python
            >>> my_data = '''
            ... <rdf:RDF
            ...   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            ...   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
            ... >
            ...   <rdf:Description>
            ...     <rdfs:label>Example</rdfs:label>
            ...     <rdfs:comment>This is really just an example.</rdfs:comment>
            ...   </rdf:Description>
            ... </rdf:RDF>
            ... '''
            >>> import os, tempfile
            >>> fd, file_name = tempfile.mkstemp()
            >>> f = os.fdopen(fd, "w")
            >>> dummy = f.write(my_data)  # Returns num bytes written
            >>> f.close()

            >>> g = Graph()
            >>> result = g.parse(data=my_data, format="application/rdf+xml")
            >>> len(g)
            2

            >>> g = Graph()
            >>> result = g.parse(location=file_name, format="application/rdf+xml")
            >>> len(g)
            2

            >>> g = Graph()
            >>> with open(file_name, "r") as f:
            ...     result = g.parse(f, format="application/rdf+xml")
            >>> len(g)
            2

            >>> os.remove(file_name)

            >>> # default turtle parsing
            >>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
            >>> len(g)
            3

            ```

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

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

            For information on available security measures, see the RDFLib
            [Security Considerations](../security_considerations.md)
            documentation.
        """

        source = create_input_source(
            source=source,
            publicID=publicID,
            location=location,
            file=file,
            data=data,
            format=format,
        )
        if format is None:
            format = source.content_type
        could_not_guess_format = False
        if format is None:
            if (
                hasattr(source, "file")
                and getattr(source.file, "name", None)
                and isinstance(source.file.name, str)
            ):
                format = rdflib.util.guess_format(source.file.name)
            if format is None:
                format = "turtle"
                could_not_guess_format = True
        try:
            parser = plugin.get(format, Parser)()
        except plugin.PluginException:
            # Handle the case when a URLInputSource returns RDF but with the headers
            # as a format that does not exist in the plugin system.
            # Use guess_format to guess the format based on the input's file suffix.
            format = rdflib.util.guess_format(
                source if not isinstance(source, InputSource) else str(source)
            )
            if format is None:
                raise
            parser = plugin.get(format, Parser)()
        try:
            # TODO FIXME: Parser.parse should have **kwargs argument.
            parser.parse(source, self, **args)
        except SyntaxError as se:
            if could_not_guess_format:
                raise ParserError(
                    "Could not guess RDF format for %r from file extension so tried Turtle but failed."
                    "You can explicitly specify format using the format argument."
                    % source
                )
            else:
                raise se
        finally:
            if source.auto_close:
                source.close()
        return self

### `` predicate_objects

    predicate_objects(subject: Optional[_SubjectType] = None, unique: bool = False) -> Generator[Tuple[_PredicateType, _ObjectType], None, None]

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

Source code in `rdflib/graph.py`

    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088

    def predicate_objects(
        self, subject: Optional[_SubjectType] = None, unique: bool = False
    ) -> Generator[Tuple[_PredicateType, _ObjectType], None, None]:
        """A generator of (optionally unique) (predicate, object) tuples
        for the given subject"""
        if not unique:
            for s, p, o in self.triples((subject, None, None)):
                yield p, o
        else:
            pred_objs = set()
            for s, p, o in self.triples((subject, None, None)):
                if (p, o) not in pred_objs:
                    yield p, o
                    try:
                        pred_objs.add((p, o))
                    except MemoryError as e:
                        logger.error(
                            f"{e}. Consider not setting parameter 'unique' to True"
                        )
                        raise

### `` predicates

    predicates(subject: Optional[_SubjectType] = None, object: Optional[_ObjectType] = None, unique: bool = False) -> Generator[_PredicateType, None, None]

Generate predicates with the given subject and object.

Parameters:

- #### `subject`

  (`Optional[_SubjectType]`, default: `None` ) –

  A specific subject to match or None to match any subject.

- #### `object`

  (`Optional[_ObjectType]`, default: `None` ) –

  A specific object to match or None to match any object.

- #### `unique`

  (`bool`, default: `False` ) –

  If True, only yield unique predicates.

Yields:

- `_PredicateType` –

  Predicates matching the given subject and object.

Source code in `rdflib/graph.py`

    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985

    def predicates(
        self,
        subject: Optional[_SubjectType] = None,
        object: Optional[_ObjectType] = None,
        unique: bool = False,
    ) -> Generator[_PredicateType, None, None]:
        """Generate predicates with the given subject and object.

        Args:
            subject: A specific subject to match or None to match any subject.
            object: A specific object to match or None to match any object.
            unique: If True, only yield unique predicates.

        Yields:
            Predicates matching the given subject and object.
        """
        if not unique:
            for s, p, o in self.triples((subject, None, object)):
                yield p
        else:
            preds = set()
            for s, p, o in self.triples((subject, None, object)):
                if p not in preds:
                    yield p
                    try:
                        preds.add(p)
                    except MemoryError as e:
                        logger.error(
                            f"{e}. Consider not setting parameter 'unique' to True"
                        )
                        raise

### `` print

    print(format: str = 'turtle', encoding: str = 'utf-8', out: Optional[TextIO] = None) -> None

Source code in `rdflib/graph.py`

    1515
    1516
    1517
    1518
    1519
    1520
    1521
    1522
    1523
    1524
    1525

    def print(
        self,
        format: str = "turtle",
        encoding: str = "utf-8",
        out: Optional[TextIO] = None,
    ) -> None:
        print(
            self.serialize(None, format=format, encoding=encoding).decode(encoding),
            file=out,
            flush=True,
        )

### `` qname

    qname(uri: str) -> str

Source code in `rdflib/graph.py`

    1337
    1338

    def qname(self, uri: str) -> str:
        return self.namespace_manager.qname(uri)

### `` query

    query(query_object: Union[str, Query], processor: Union[str, Processor] = 'sparql', result: Union[str, Type[Result]] = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs: Any) -> Result

Query this graph.

Parameters:

- #### `query_object`

  (`Union[str, Query]`) –

  The query string or object to execute.

- #### `processor`

  (`Union[str, Processor]`, default: `'sparql'` ) –

  The query processor to use. Default is “sparql”.

- #### `result`

  (`Union[str, Type[Result]]`, default: `'sparql'` ) –

  The result format to use. Default is “sparql”.

- #### `initNs`

  (`Optional[Mapping[str, Any]]`, default: `None` ) –

  Initial namespaces to use for resolving prefixes in the query. If none are given, the namespaces from the graph’s namespace manager are used.

- #### `initBindings`

  (`Optional[Mapping[str, Identifier]]`, default: `None` ) –

  Initial variable bindings to use. A type of ‘prepared queries’ can be realized by providing these bindings.

- #### `use_store_provided`

  (`bool`, default: `True` ) –

  Whether to use the store’s query method if available.

- #### `kwargs`

  (`Any`, default: `{}` ) –

  Additional arguments to pass to the query processor.

Returns:

- `Result` –

  A [`rdflib.query.Result`][`rdflib.query.Result`] instance.

Caution

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

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

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

Source code in `rdflib/graph.py`

    1675
    1676
    1677
    1678
    1679
    1680
    1681
    1682
    1683
    1684
    1685
    1686
    1687
    1688
    1689
    1690
    1691
    1692
    1693
    1694
    1695
    1696
    1697
    1698
    1699
    1700
    1701
    1702
    1703
    1704
    1705
    1706
    1707
    1708
    1709
    1710
    1711
    1712
    1713
    1714
    1715
    1716
    1717
    1718
    1719
    1720
    1721
    1722
    1723
    1724
    1725
    1726
    1727
    1728
    1729
    1730
    1731
    1732
    1733
    1734
    1735
    1736
    1737
    1738
    1739
    1740
    1741
    1742

    def query(
        self,
        query_object: Union[str, Query],
        processor: Union[str, query.Processor] = "sparql",
        result: Union[str, Type[query.Result]] = "sparql",
        initNs: Optional[Mapping[str, Any]] = None,  # noqa: N803
        initBindings: Optional[Mapping[str, Identifier]] = None,  # noqa: N803
        use_store_provided: bool = True,
        **kwargs: Any,
    ) -> query.Result:
        """
        Query this graph.

        Args:
            query_object: The query string or object to execute.
            processor: The query processor to use. Default is "sparql".
            result: The result format to use. Default is "sparql".
            initNs: Initial namespaces to use for resolving prefixes in the query.
                If none are given, the namespaces from the graph's namespace manager are used.
            initBindings: Initial variable bindings to use. A type of 'prepared queries'
                can be realized by providing these bindings.
            use_store_provided: Whether to use the store's query method if available.
            kwargs: Additional arguments to pass to the query processor.

        Returns:
            A [`rdflib.query.Result`][`rdflib.query.Result`] instance.

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

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

            For information on available security measures, see the RDFLib
            [Security Considerations](../security_considerations.md)
            documentation.
        """

        initBindings = initBindings or {}  # noqa: N806
        initNs = initNs or dict(self.namespaces())  # noqa: N806

        if self.default_union:
            query_graph = "__UNION__"
        elif isinstance(self, ConjunctiveGraph):
            query_graph = self.default_context.identifier
        else:
            query_graph = self.identifier
        if hasattr(self.store, "query") and use_store_provided:
            try:
                return self.store.query(
                    query_object,
                    initNs,
                    initBindings,
                    query_graph,
                    **kwargs,
                )
            except NotImplementedError:
                pass  # store has no own implementation

        if not isinstance(result, query.Result):
            result = plugin.get(cast(str, result), query.Result)
        if not isinstance(processor, query.Processor):
            processor = plugin.get(processor, query.Processor)(self)

        # type error: Argument 1 to "Result" has incompatible type "Mapping[str, Any]"; expected "str"
        return result(processor.query(query_object, initBindings, initNs, **kwargs))  # type: ignore[arg-type]

### `` remove

    remove(triple: _TriplePatternType) -> _GraphT

Remove a triple from the graph

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

Source code in `rdflib/graph.py`

    645
    646
    647
    648
    649
    650
    651
    652

    def remove(self: _GraphT, triple: _TriplePatternType) -> _GraphT:
        """Remove a triple from the graph

        If the triple does not provide a context attribute, removes the triple
        from all contexts.
        """
        self.__store.remove(triple, context=self)
        return self

### `` resource

    resource(identifier: Union[Node, str]) -> Resource

Create a new `Resource` instance.

Parameters:

- #### `identifier`

  (`Union[Node, str]`) –

  A URIRef or BNode instance.

Returns:

- `Resource` –

  A new Resource 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

Source code in `rdflib/graph.py`

    1915
    1916
    1917
    1918
    1919
    1920
    1921
    1922
    1923
    1924
    1925
    1926
    1927
    1928
    1929
    1930
    1931
    1932
    1933
    1934
    1935
    1936
    1937

    def resource(self, identifier: Union[Node, str]) -> Resource:
        """Create a new ``Resource`` instance.

        Args:
            identifier: A URIRef or BNode instance.

        Returns:
            A new Resource instance.

        Example:
            ```python
            >>> 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

            ```
        """
        if not isinstance(identifier, Node):
            identifier = URIRef(identifier)
        return Resource(self, identifier)

### `` rollback

    rollback() -> _GraphT

Rollback active transactions

Source code in `rdflib/graph.py`

    594
    595
    596
    597

    def rollback(self: _GraphT) -> _GraphT:
        """Rollback active transactions"""
        self.__store.rollback()
        return self

### `` serialize

    serialize(destination: Optional[Union[str, PurePath, IO[bytes]]] = None, format: str = 'turtle', base: Optional[str] = None, encoding: Optional[str] = None, **args: Any) -> Union[bytes, str, _GraphT]

Serialize the graph.

Parameters:

- #### `destination`

  (`Optional[Union[str, PurePath, IO[bytes]]]`, default: `None` ) –

  The destination to serialize the graph to. This can be a path as a string or pathlib.PurePath object, or it can be an IO[bytes] like object. If this parameter is not supplied the serialized graph will be returned.

- #### `format`

  (`str`, default: `'turtle'` ) –

  The format that the output should be written in. This value references a Serializer plugin. Format support is managed with plugins. Defaults to “turtle” and some other formats are builtin, like “xml” and “trix”. See also serialize module.

- #### `base`

  (`Optional[str]`, default: `None` ) –

  The base IRI for formats that support it. For the turtle format this will be used as the @base directive.

- #### `encoding`

  (`Optional[str]`, default: `None` ) –

  Encoding of output.

- #### `args`

  (`Any`, default: `{}` ) –

  Additional arguments to pass to the Serializer that will be used.

Returns:

- `Union[bytes, str, _GraphT]` –

  The serialized graph if `destination` is None. The serialized graph is returned

- `Union[bytes, str, _GraphT]` –

  as str if no encoding is specified, and as bytes if an encoding is specified.

- `Union[bytes, str, _GraphT]` –

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

Source code in `rdflib/graph.py`

    1448
    1449
    1450
    1451
    1452
    1453
    1454
    1455
    1456
    1457
    1458
    1459
    1460
    1461
    1462
    1463
    1464
    1465
    1466
    1467
    1468
    1469
    1470
    1471
    1472
    1473
    1474
    1475
    1476
    1477
    1478
    1479
    1480
    1481
    1482
    1483
    1484
    1485
    1486
    1487
    1488
    1489
    1490
    1491
    1492
    1493
    1494
    1495
    1496
    1497
    1498
    1499
    1500
    1501
    1502
    1503
    1504
    1505
    1506
    1507
    1508
    1509
    1510
    1511
    1512
    1513

    def serialize(
        self: _GraphT,
        destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None,
        format: str = "turtle",
        base: Optional[str] = None,
        encoding: Optional[str] = None,
        **args: Any,
    ) -> Union[bytes, str, _GraphT]:
        """Serialize the graph.

        Args:
            destination: The destination to serialize the graph to. This can be a path as a
                string or pathlib.PurePath object, or it can be an IO[bytes] like object.
                If this parameter is not supplied the serialized graph will be returned.
            format: The format that the output should be written in. This value
                references a Serializer plugin.
                Format support is managed with [plugins][rdflib.plugin].
                Defaults to "turtle" and some other formats are builtin,
                like "xml" and "trix".
                See also [serialize module][rdflib.plugins.parsers].
            base: The base IRI for formats that support it. For the turtle format this
                will be used as the @base directive.
            encoding: Encoding of output.
            args: Additional arguments to pass to the Serializer that will be used.

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

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

        # if base is not given as attribute use the base set for the graph
        if base is None:
            base = self.base

        serializer = plugin.get(format, Serializer)(self)
        stream: IO[bytes]
        if destination is None:
            stream = BytesIO()
            if encoding is None:
                serializer.serialize(stream, base=base, encoding="utf-8", **args)
                return stream.getvalue().decode("utf-8")
            else:
                serializer.serialize(stream, base=base, encoding=encoding, **args)
                return stream.getvalue()
        if hasattr(destination, "write"):
            stream = cast(IO[bytes], destination)
            serializer.serialize(stream, base=base, encoding=encoding, **args)
        else:
            if isinstance(destination, pathlib.PurePath):
                os_path = str(destination)
            else:
                location = cast(str, destination)
                scheme, netloc, path, params, _query, fragment = urlparse(location)
                if scheme == "file":
                    if netloc != "":
                        raise ValueError(
                            f"the file URI {location!r} has an authority component which is not supported"
                        )
                    os_path = url2pathname(path)
                else:
                    os_path = location
            with open(os_path, "wb") as stream:
                serializer.serialize(stream, base=base, encoding=encoding, **args)
        return self

### `` set

    set(triple: Tuple[_SubjectType, _PredicateType, _ObjectType]) -> _GraphT

Convenience method to update the value of object

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

Source code in `rdflib/graph.py`

    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917

    def set(
        self: _GraphT, triple: Tuple[_SubjectType, _PredicateType, _ObjectType]
    ) -> _GraphT:
        """Convenience method to update the value of object

        Remove any existing triples for subject and predicate before adding
        (subject, predicate, object).
        """
        (subject, predicate, object_) = triple
        assert (
            subject is not None
        ), "s can't be None in .set([s,p,o]), as it would remove (*, p, *)"
        assert (
            predicate is not None
        ), "p can't be None in .set([s,p,o]), as it would remove (s, *, *)"
        self.remove((subject, predicate, None))
        self.add((subject, predicate, object_))
        return self

### `` skolemize

    skolemize(new_graph: Optional[Graph] = None, bnode: Optional[BNode] = None, authority: Optional[str] = None, basepath: Optional[str] = None) -> Graph

Source code in `rdflib/graph.py`

    1945
    1946
    1947
    1948
    1949
    1950
    1951
    1952
    1953
    1954
    1955
    1956
    1957
    1958
    1959
    1960
    1961
    1962
    1963
    1964
    1965
    1966
    1967
    1968
    1969
    1970
    1971
    1972
    1973
    1974
    1975
    1976
    1977
    1978
    1979
    1980

    def skolemize(
        self,
        new_graph: Optional[Graph] = None,
        bnode: Optional[BNode] = None,
        authority: Optional[str] = None,
        basepath: Optional[str] = None,
    ) -> Graph:
        def do_skolemize(bnode: BNode, t: _TripleType) -> _TripleType:
            (s, p, o) = t
            if s == bnode:
                if TYPE_CHECKING:
                    assert isinstance(s, BNode)
                s = s.skolemize(authority=authority, basepath=basepath)
            if o == bnode:
                if TYPE_CHECKING:
                    assert isinstance(o, BNode)
                o = o.skolemize(authority=authority, basepath=basepath)
            return s, p, o

        def do_skolemize2(t: _TripleType) -> _TripleType:
            (s, p, o) = t
            if isinstance(s, BNode):
                s = s.skolemize(authority=authority, basepath=basepath)
            if isinstance(o, BNode):
                o = o.skolemize(authority=authority, basepath=basepath)
            return s, p, o

        retval = Graph() if new_graph is None else new_graph

        if bnode is None:
            self._process_skolem_tuples(retval, do_skolemize2)
        elif isinstance(bnode, BNode):
            # type error: Argument 1 to "do_skolemize" has incompatible type "Optional[BNode]"; expected "BNode"
            self._process_skolem_tuples(retval, lambda t: do_skolemize(bnode, t))  # type: ignore[arg-type, unused-ignore]

        return retval

### `` subject_objects

    subject_objects(predicate: Union[None, Path, _PredicateType] = None, unique: bool = False) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]

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

Source code in `rdflib/graph.py`

    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067

    def subject_objects(
        self,
        predicate: Union[None, Path, _PredicateType] = None,
        unique: bool = False,
    ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]:
        """A generator of (optionally unique) (subject, object) tuples
        for the given predicate"""
        if not unique:
            for s, p, o in self.triples((None, predicate, None)):
                yield s, o
        else:
            subj_objs = set()
            for s, p, o in self.triples((None, predicate, None)):
                if (s, o) not in subj_objs:
                    yield s, o
                    try:
                        subj_objs.add((s, o))
                    except MemoryError as e:
                        logger.error(
                            f"{e}. Consider not setting parameter 'unique' to True"
                        )
                        raise

### `` subject_predicates

    subject_predicates(object: Optional[_ObjectType] = None, unique: bool = False) -> Generator[Tuple[_SubjectType, _PredicateType], None, None]

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

Source code in `rdflib/graph.py`

    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044

    def subject_predicates(
        self, object: Optional[_ObjectType] = None, unique: bool = False
    ) -> Generator[Tuple[_SubjectType, _PredicateType], None, None]:
        """A generator of (optionally unique) (subject, predicate) tuples
        for the given object"""
        if not unique:
            for s, p, o in self.triples((None, None, object)):
                yield s, p
        else:
            subj_preds = set()
            for s, p, o in self.triples((None, None, object)):
                if (s, p) not in subj_preds:
                    yield s, p
                    try:
                        subj_preds.add((s, p))
                    except MemoryError as e:
                        logger.error(
                            f"{e}. Consider not setting parameter 'unique' to True"
                        )
                        raise

### `` subjects

    subjects(predicate: Union[None, Path, _PredicateType] = None, object: Optional[Union[_ObjectType, List[_ObjectType]]] = None, unique: bool = False) -> Generator[_SubjectType, None, None]

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

Parameters:

- #### `predicate`

  (`Union[None, Path, _PredicateType]`, default: `None` ) –

  A specific predicate to match or None to match any predicate.

- #### `object`

  (`Optional[Union[_ObjectType, List[_ObjectType]]]`, default: `None` ) –

  A specific object or list of objects to match or None to match any object.

- #### `unique`

  (`bool`, default: `False` ) –

  If True, only yield unique subjects.

Source code in `rdflib/graph.py`

    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953

    def subjects(
        self,
        predicate: Union[None, Path, _PredicateType] = None,
        object: Optional[Union[_ObjectType, List[_ObjectType]]] = None,
        unique: bool = False,
    ) -> Generator[_SubjectType, None, None]:
        """A generator of (optionally unique) subjects with the given
        predicate and object(s)

        Args:
            predicate: A specific predicate to match or None to match any predicate.
            object: A specific object or list of objects to match or None to match any object.
            unique: If True, only yield unique subjects.
        """
        # if the object is a list of Nodes, yield results from subject() call for each
        if isinstance(object, list):
            for obj in object:
                for s in self.subjects(predicate, obj, unique):
                    yield s
        else:
            if not unique:
                for s, p, o in self.triples((None, predicate, object)):
                    yield s
            else:
                subs = set()
                for s, p, o in self.triples((None, predicate, object)):
                    if s not in subs:
                        yield s
                        try:
                            subs.add(s)
                        except MemoryError as e:
                            logger.error(
                                f"{e}. Consider not setting parameter 'unique' to True"
                            )
                            raise

### `` toPython

    toPython() -> _GraphT

Source code in `rdflib/graph.py`

    580
    581

    def toPython(self: _GraphT) -> _GraphT:  # noqa: N802
        return self

### `` transitiveClosure

    transitiveClosure(func: Callable[[_TCArgT, Graph], Iterable[_TCArgT]], arg: _TCArgT, seen: Optional[Dict[_TCArgT, int]] = 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,namespace.RDFS.label))
    g.add((b,RDF.rest,c))
    g.add((c,RDF.first,namespace.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)]
    # [rdflib.term.BNode('baz'),
    #  rdflib.term.BNode('bar'),
    #  rdflib.term.BNode('foo')]

    [rt for rt in g.transitiveClosure(
        reverseList,RDF.nil)]
    # http://www.w3.org/2000/01/rdf-schema#comment
    # http://www.w3.org/2000/01/rdf-schema#label
    # http://www.w3.org/1999/02/22-rdf-syntax-ns#type
    # [rdflib.term.BNode('baz'),
    #  rdflib.term.BNode('bar'),
    #  rdflib.term.BNode('foo')]

Parameters:

- #### `func`

  (`Callable[[_TCArgT, Graph], Iterable[_TCArgT]]`) –

  A function that generates a sequence of nodes

- #### `arg`

  (`_TCArgT`) –

  The starting node

- #### `seen`

  (`Optional[Dict[_TCArgT, int]]`, default: `None` ) –

  A dict of visited nodes

Source code in `rdflib/graph.py`

    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283

    def transitiveClosure(  # noqa: N802
        self,
        func: Callable[[_TCArgT, Graph], Iterable[_TCArgT]],
        arg: _TCArgT,
        seen: Optional[Dict[_TCArgT, int]] = None,
    ):
        """Generates transitive closure of a user-defined function against the graph

        ```python
        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,namespace.RDFS.label))
        g.add((b,RDF.rest,c))
        g.add((c,RDF.first,namespace.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)]
        # [rdflib.term.BNode('baz'),
        #  rdflib.term.BNode('bar'),
        #  rdflib.term.BNode('foo')]

        [rt for rt in g.transitiveClosure(
            reverseList,RDF.nil)]
        # http://www.w3.org/2000/01/rdf-schema#comment
        # http://www.w3.org/2000/01/rdf-schema#label
        # http://www.w3.org/1999/02/22-rdf-syntax-ns#type
        # [rdflib.term.BNode('baz'),
        #  rdflib.term.BNode('bar'),
        #  rdflib.term.BNode('foo')]
        ```

        Args:
            func: A function that generates a sequence of nodes
            arg: The starting node
            seen: A dict of visited nodes
        """
        if seen is None:
            seen = {}
        elif arg in seen:
            return
        seen[arg] = 1
        for rt in func(arg, self):
            yield rt
            for rt_2 in self.transitiveClosure(func, rt, seen):
                yield rt_2

### `` transitive_objects

    transitive_objects(subject: Optional[_SubjectType], predicate: Optional[_PredicateType], remember: Optional[Dict[Optional[_SubjectType], int]] = None) -> Generator[Optional[_SubjectType], None, None]

Transitively generate objects for the `predicate` relationship

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

Parameters:

- #### `subject`

  (`Optional[_SubjectType]`) –

  The subject to start the transitive closure from

- #### `predicate`

  (`Optional[_PredicateType]`) –

  The predicate to follow

- #### `remember`

  (`Optional[Dict[Optional[_SubjectType], int]]`, default: `None` ) –

  A dict of visited nodes

Source code in `rdflib/graph.py`

    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309

    def transitive_objects(
        self,
        subject: Optional[_SubjectType],
        predicate: Optional[_PredicateType],
        remember: Optional[Dict[Optional[_SubjectType], int]] = None,
    ) -> Generator[Optional[_SubjectType], None, None]:
        """Transitively generate objects for the ``predicate`` relationship

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

        Args:
            subject: The subject to start the transitive closure from
            predicate: The predicate to follow
            remember: A dict of visited nodes
        """
        if remember is None:
            remember = {}
        if subject in remember:
            return
        remember[subject] = 1
        yield subject
        for object in self.objects(subject, predicate):
            for o in self.transitive_objects(object, predicate, remember):
                yield o

### `` transitive_subjects

    transitive_subjects(predicate: Optional[_PredicateType], object: Optional[_ObjectType], remember: Optional[Dict[Optional[_ObjectType], int]] = None) -> Generator[Optional[_ObjectType], None, None]

Transitively generate subjects for the `predicate` relationship

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

Parameters:

- #### `predicate`

  (`Optional[_PredicateType]`) –

  The predicate to follow

- #### `object`

  (`Optional[_ObjectType]`) –

  The object to start the transitive closure from

- #### `remember`

  (`Optional[Dict[Optional[_ObjectType], int]]`, default: `None` ) –

  A dict of visited nodes

Source code in `rdflib/graph.py`

    1311
    1312
    1313
    1314
    1315
    1316
    1317
    1318
    1319
    1320
    1321
    1322
    1323
    1324
    1325
    1326
    1327
    1328
    1329
    1330
    1331
    1332
    1333
    1334
    1335

    def transitive_subjects(
        self,
        predicate: Optional[_PredicateType],
        object: Optional[_ObjectType],
        remember: Optional[Dict[Optional[_ObjectType], int]] = None,
    ) -> Generator[Optional[_ObjectType], None, None]:
        """Transitively generate subjects for the ``predicate`` relationship

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

        Args:
            predicate: The predicate to follow
            object: The object to start the transitive closure from
            remember: A dict of visited nodes
        """
        if remember is None:
            remember = {}
        if object in remember:
            return
        remember[object] = 1
        yield object
        for subject in self.subjects(predicate, object):
            for s in self.transitive_subjects(predicate, subject, remember):
                yield s

### `` triples

    triples(triple: _TripleSelectorType) -> Generator[_TripleOrTriplePathType, None, None]

Generator over the triple store.

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

Parameters:

- #### `triple`

  (`_TripleSelectorType`) –

  A triple pattern where each component can be a specific value or None as a wildcard. The predicate can also be a path expression.

Yields:

- `_TripleOrTriplePathType` –

  Triples matching the given pattern.

Source code in `rdflib/graph.py`

    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694

    def triples(
        self,
        triple: _TripleSelectorType,
    ) -> Generator[_TripleOrTriplePathType, None, None]:
        """Generator over the triple store.

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

        Args:
            triple: A triple pattern where each component can be a specific value or None
                as a wildcard. The predicate can also be a path expression.

        Yields:
            Triples matching the given pattern.
        """
        s, p, o = triple
        if isinstance(p, Path):
            for _s, _o in p.eval(self, s, o):
                yield _s, p, _o
        else:
            for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self):
                yield _s, _p, _o

### `` triples_choices

    triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]

Source code in `rdflib/graph.py`

    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101

    def triples_choices(
        self,
        triple: _TripleChoiceType,
        context: Optional[_ContextType] = None,
    ) -> Generator[_TripleType, None, None]:
        subject, predicate, object_ = triple
        # type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
        # type error note: unpacking discards type info
        for (s, p, o), cg in self.store.triples_choices(
            (subject, predicate, object_), context=self  # type: ignore[arg-type]
        ):
            yield s, p, o

### `` update

    update(update_object: Union[Update, str], processor: Union[str, UpdateProcessor] = 'sparql', initNs: Optional[Mapping[str, Any]] = None, initBindings: Optional[Mapping[str, Identifier]] = None, use_store_provided: bool = True, **kwargs: Any) -> None

Update this graph with the given update query.

Parameters:

- #### `update_object`

  (`Union[Update, str]`) –

  The update query string or object to execute.

- #### `processor`

  (`Union[str, UpdateProcessor]`, default: `'sparql'` ) –

  The update processor to use. Default is “sparql”.

- #### `initNs`

  (`Optional[Mapping[str, Any]]`, default: `None` ) –

  Initial namespaces to use for resolving prefixes in the query. If none are given, the namespaces from the graph’s namespace manager are used.

- #### `initBindings`

  (`Optional[Mapping[str, Identifier]]`, default: `None` ) –

  Initial variable bindings to use.

- #### `use_store_provided`

  (`bool`, default: `True` ) –

  Whether to use the store’s update method if available.

- #### `kwargs`

  (`Any`, default: `{}` ) –

  Additional arguments to pass to the update processor.

Caution

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

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

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

Source code in `rdflib/graph.py`

    1744
    1745
    1746
    1747
    1748
    1749
    1750
    1751
    1752
    1753
    1754
    1755
    1756
    1757
    1758
    1759
    1760
    1761
    1762
    1763
    1764
    1765
    1766
    1767
    1768
    1769
    1770
    1771
    1772
    1773
    1774
    1775
    1776
    1777
    1778
    1779
    1780
    1781
    1782
    1783
    1784
    1785
    1786
    1787
    1788
    1789
    1790
    1791
    1792
    1793
    1794
    1795
    1796
    1797
    1798
    1799
    1800

    def update(
        self,
        update_object: Union[Update, str],
        processor: Union[str, rdflib.query.UpdateProcessor] = "sparql",
        initNs: Optional[Mapping[str, Any]] = None,  # noqa: N803
        initBindings: Optional[Mapping[str, Identifier]] = None,  # noqa: N803
        use_store_provided: bool = True,
        **kwargs: Any,
    ) -> None:
        """Update this graph with the given update query.

        Args:
            update_object: The update query string or object to execute.
            processor: The update processor to use. Default is "sparql".
            initNs: Initial namespaces to use for resolving prefixes in the query.
                If none are given, the namespaces from the graph's namespace manager are used.
            initBindings: Initial variable bindings to use.
            use_store_provided: Whether to use the store's update method if available.
            kwargs: Additional arguments to pass to the update processor.

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

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

            For information on available security measures, see the RDFLib
            Security Considerations documentation.
        """
        initBindings = initBindings or {}  # noqa: N806
        initNs = initNs or dict(self.namespaces())  # noqa: N806

        if self.default_union:
            query_graph = "__UNION__"
        elif isinstance(self, ConjunctiveGraph):
            query_graph = self.default_context.identifier
        else:
            query_graph = self.identifier

        if hasattr(self.store, "update") and use_store_provided:
            try:
                return self.store.update(
                    update_object,
                    initNs,
                    initBindings,
                    query_graph,
                    **kwargs,
                )
            except NotImplementedError:
                pass  # store has no own implementation

        if not isinstance(processor, query.UpdateProcessor):
            processor = plugin.get(processor, query.UpdateProcessor)(self)

        return processor.update(update_object, initBindings, initNs, **kwargs)

### `` value

    value(subject: Optional[_SubjectType] = None, predicate: Optional[_PredicateType] = value, object: Optional[_ObjectType] = None, default: Optional[Node] = None, any: bool = True) -> Optional[Node]

Get a value for a pair of two criteria

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

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

Parameters:

- #### `subject`

  (`Optional[_SubjectType]`, default: `None` ) –

  Subject of the triple pattern, exactly one of subject, predicate, object must be None

- #### `predicate`

  (`Optional[_PredicateType]`, default: `value` ) –

  Predicate of the triple pattern, exactly one of subject, predicate, object must be None

- #### `object`

  (`Optional[_ObjectType]`, default: `None` ) –

  Object of the triple pattern, exactly one of subject, predicate, object must be None

- #### `default`

  (`Optional[Node]`, default: `None` ) –

  Value to be returned if no values found

- #### `any`

  (`bool`, default: `True` ) –

  If True, return any value in the case there is more than one, else, raise UniquenessError

Source code in `rdflib/graph.py`

    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206

    def value(
        self,
        subject: Optional[_SubjectType] = None,
        predicate: Optional[_PredicateType] = RDF.value,
        object: Optional[_ObjectType] = None,
        default: Optional[Node] = None,
        any: bool = True,
    ) -> Optional[Node]:
        """Get a value for a pair of two criteria

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

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

        Args:
            subject: Subject of the triple pattern, exactly one of subject, predicate, object must be None
            predicate: Predicate of the triple pattern, exactly one of subject, predicate, object must be None
            object: Object of the triple pattern, exactly one of subject, predicate, object 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
        """
        retval = default

        if (
            (subject is None and predicate is None)
            or (subject is None and object is None)
            or (predicate is None and object is None)
        ):
            return None

        if object is None:
            values = self.objects(subject, predicate)
        if subject is None:
            values = self.subjects(predicate, object)
        if predicate is None:
            values = self.predicates(subject, object)

        try:
            retval = next(values)
        except StopIteration:
            retval = default
        else:
            if any is False:
                try:
                    next(values)
                    msg = (
                        "While trying to find a value for (%s, %s, %s) the"
                        " following multiple values where found:\n"
                        % (subject, predicate, object)
                    )
                    triples = self.store.triples((subject, predicate, object), None)
                    for (s, p, o), contexts in triples:
                        msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
                            s,
                            p,
                            o,
                            list(contexts),
                        )
                    raise exceptions.UniquenessError(msg)
                except StopIteration:
                    pass
        return retval

## `` ModificationException

    ModificationException()

Bases: `Exception`

Methods:

- `__str__` –

Source code in `rdflib/graph.py`

    3085
    3086

    def __init__(self) -> None:
        pass

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    3088
    3089
    3090
    3091
    3092

    def __str__(self) -> str:
        return (
            "Modifications and transactional operations not allowed on "
            "ReadOnlyGraphAggregate instances"
        )

## `` QuotedGraph

    QuotedGraph(store: Union[Store, str], identifier: Optional[Union[_ContextIdentifierType, str]])

Bases: `Graph`

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

Methods:

- `__reduce__` –
- `__str__` –
- `add` –

  Add a triple with self as context

- `addN` –

  Add a sequence of triple with context

- `n3` –

  Return an n3 identifier for the Graph

Source code in `rdflib/graph.py`

    2983
    2984
    2985
    2986
    2987
    2988

    def __init__(
        self,
        store: Union[Store, str],
        identifier: Optional[Union[_ContextIdentifierType, str]],
    ):
        super(QuotedGraph, self).__init__(store, identifier)

### `` __reduce__

    __reduce__() -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]

Source code in `rdflib/graph.py`

    3025
    3026

    def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
        return QuotedGraph, (self.store, self.identifier)

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    3016
    3017
    3018
    3019
    3020
    3021
    3022
    3023

    def __str__(self) -> str:
        identifier = self.identifier.n3()
        label = self.store.__class__.__name__
        pattern = (
            "{this rdflib.identifier %s;rdflib:storage "
            "[a rdflib:Store;rdfs:label '%s']}"
        )
        return pattern % (identifier, label)

### `` add

    add(triple: _TripleType) -> _GraphT

Add a triple with self as context

Source code in `rdflib/graph.py`

    2990
    2991
    2992
    2993
    2994
    2995
    2996
    2997
    2998

    def add(self: _GraphT, triple: _TripleType) -> _GraphT:
        """Add a triple with self as context"""
        s, p, o = triple
        assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,)
        assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,)
        assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,)

        self.store.add((s, p, o), self, quoted=True)
        return self

### `` addN

    addN(quads: Iterable[_QuadType]) -> _GraphT

Add a sequence of triple with context

Source code in `rdflib/graph.py`

    3000
    3001
    3002
    3003
    3004
    3005
    3006
    3007
    3008
    3009
    3010

    def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT:  # noqa: N802
        """Add a sequence of triple with context"""

        self.store.addN(
            (s, p, o, c)
            for s, p, o, c in quads
            if isinstance(c, QuotedGraph)
            and c.identifier is self.identifier
            and _assertnode(s, p, o)
        )
        return self

### `` n3

    n3(namespace_manager: Optional[NamespaceManager] = None) -> str

Return an n3 identifier for the Graph

Source code in `rdflib/graph.py`

    3012
    3013
    3014

    def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str:
        """Return an n3 identifier for the Graph"""
        return "{%s}" % self.identifier.n3(namespace_manager=namespace_manager)

## `` ReadOnlyGraphAggregate

    ReadOnlyGraphAggregate(graphs: List[Graph], store: Union[str, Store] = 'default')

Bases: `ConjunctiveGraph`

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

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

Methods:

- `__cmp__` –
- `__contains__` –
- `__hash__` –
- `__iadd__` –
- `__isub__` –
- `__len__` –
- `__reduce__` –
- `__repr__` –
- `absolutize` –
- `add` –
- `addN` –
- `bind` –
- `close` –
- `commit` –
- `compute_qname` –
- `destroy` –
- `n3` –
- `namespaces` –
- `open` –
- `parse` –
- `qname` –
- `quads` –

  Iterate over all the quads in the entire aggregate graph

- `remove` –
- `rollback` –
- `triples` –
- `triples_choices` –

Attributes:

- `graphs` –

Source code in `rdflib/graph.py`

    3110
    3111
    3112
    3113
    3114
    3115
    3116
    3117
    3118
    3119
    3120
    3121

    def __init__(self, graphs: List[Graph], store: Union[str, Store] = "default"):
        if store is not None:
            super(ReadOnlyGraphAggregate, self).__init__(store)
            Graph.__init__(self, store)
            self.__namespace_manager = None

        assert (
            isinstance(graphs, list)
            and graphs
            and [g for g in graphs if isinstance(g, Graph)]
        ), "graphs argument must be a list of Graphs!!"
        self.graphs = graphs

### `` __namespace_manager `instance-attribute`

    __namespace_manager = None

### `` graphs `instance-attribute`

    graphs = graphs

### `` __cmp__

    __cmp__(other) -> int

Source code in `rdflib/graph.py`

    3234
    3235
    3236
    3237
    3238
    3239
    3240
    3241
    3242

    def __cmp__(self, other) -> int:
        if other is None:
            return -1
        elif isinstance(other, Graph):
            return -1
        elif isinstance(other, ReadOnlyGraphAggregate):
            return (self.graphs > other.graphs) - (self.graphs < other.graphs)
        else:
            return -1

### `` __contains__

    __contains__(triple_or_quad: _TripleOrQuadSelectorType) -> bool

Source code in `rdflib/graph.py`

    3191
    3192
    3193
    3194
    3195
    3196
    3197
    3198
    3199
    3200

    def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool:
        context = None
        if len(triple_or_quad) == 4:
            # type error: Tuple index out of range
            context = triple_or_quad[3]  # type: ignore [misc, unused-ignore]
        for graph in self.graphs:
            if context is None or graph.identifier == context.identifier:
                if triple_or_quad[:3] in graph:
                    return True
        return False

### `` __hash__

    __hash__() -> NoReturn

Source code in `rdflib/graph.py`

    3231
    3232

    def __hash__(self) -> NoReturn:
        raise UnSupportedAggregateOperation()

### `` __iadd__

    __iadd__(other: Iterable[_TripleType]) -> NoReturn

Source code in `rdflib/graph.py`

    3244
    3245

    def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn:
        raise ModificationException()

### `` __isub__

    __isub__(other: Iterable[_TripleType]) -> NoReturn

Source code in `rdflib/graph.py`

    3247
    3248

    def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn:
        raise ModificationException()

### `` __len__

    __len__() -> int

Source code in `rdflib/graph.py`

    3228
    3229

    def __len__(self) -> int:
        return sum(len(g) for g in self.graphs)

### `` __reduce__

    __reduce__() -> NoReturn

Source code in `rdflib/graph.py`

    3308
    3309

    def __reduce__(self) -> NoReturn:
        raise UnSupportedAggregateOperation()

### `` __repr__

    __repr__() -> str

Source code in `rdflib/graph.py`

    3123
    3124

    def __repr__(self) -> str:
        return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)

### `` absolutize

    absolutize(uri: str, defrag: int = 1) -> NoReturn

Source code in `rdflib/graph.py`

    3290
    3291

    def absolutize(self, uri: str, defrag: int = 1) -> NoReturn:
        raise UnSupportedAggregateOperation()

### `` add

    add(triple: _TripleOrOptionalQuadType) -> NoReturn

Source code in `rdflib/graph.py`

    3149
    3150

    def add(self, triple: _TripleOrOptionalQuadType) -> NoReturn:
        raise ModificationException()

### `` addN

    addN(quads: Iterable[_QuadType]) -> NoReturn

Source code in `rdflib/graph.py`

    3152
    3153

    def addN(self, quads: Iterable[_QuadType]) -> NoReturn:  # noqa: N802
        raise ModificationException()

### `` bind

    bind(prefix: Optional[str], namespace: Any, override: bool = True) -> NoReturn

Source code in `rdflib/graph.py`

    3276
    3277
    3278
    3279

    def bind(  # type: ignore[override]
        self, prefix: Optional[str], namespace: Any, override: bool = True  # noqa: F811
    ) -> NoReturn:
        raise UnSupportedAggregateOperation()

### `` close

    close() -> None

Source code in `rdflib/graph.py`

    3145
    3146
    3147

    def close(self) -> None:  # type: ignore[override]
        for graph in self.graphs:
            graph.close()

### `` commit

    commit() -> NoReturn

Source code in `rdflib/graph.py`

    3130
    3131

    def commit(self) -> NoReturn:
        raise ModificationException()

### `` compute_qname

    compute_qname(uri: str, generate: bool = True) -> Tuple[str, URIRef, str]

Source code in `rdflib/graph.py`

    3270
    3271
    3272
    3273

    def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
        if hasattr(self, "namespace_manager") and self.namespace_manager:
            return self.namespace_manager.compute_qname(uri, generate)
        raise UnSupportedAggregateOperation()

### `` destroy

    destroy(configuration: str) -> NoReturn

Source code in `rdflib/graph.py`

    3126
    3127

    def destroy(self, configuration: str) -> NoReturn:
        raise ModificationException()

### `` n3

    n3(namespace_manager: Optional[NamespaceManager] = None) -> NoReturn

Source code in `rdflib/graph.py`

    3305
    3306

    def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> NoReturn:
        raise UnSupportedAggregateOperation()

### `` namespaces

    namespaces() -> Generator[Tuple[str, URIRef], None, None]

Source code in `rdflib/graph.py`

    3281
    3282
    3283
    3284
    3285
    3286
    3287
    3288

    def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]:
        if hasattr(self, "namespace_manager"):
            for prefix, namespace in self.namespace_manager.namespaces():
                yield prefix, namespace
        else:
            for graph in self.graphs:
                for prefix, namespace in graph.namespaces():
                    yield prefix, namespace

### `` open

    open(configuration: str | tuple[str, str], create: bool = False) -> None

Source code in `rdflib/graph.py`

    3136
    3137
    3138
    3139
    3140
    3141
    3142

    def open(self, configuration: str | tuple[str, str], create: bool = False) -> None:
        # TODO: is there a use case for this method?
        for graph in self.graphs:
            # type error: Too many arguments for "open" of "Graph"
            # type error: Argument 1 to "open" of "Graph" has incompatible type "ReadOnlyGraphAggregate"; expected "str"  [arg-type]
            # type error: Argument 2 to "open" of "Graph" has incompatible type "str"; expected "bool"  [arg-type]
            graph.open(self, configuration, create)  # type: ignore[call-arg, arg-type]

### `` parse

    parse(source: Optional[Union[IO[bytes], TextIO, InputSource, str, bytes, PurePath]], publicID: Optional[str] = None, format: Optional[str] = None, **args: Any) -> NoReturn

Source code in `rdflib/graph.py`

    3294
    3295
    3296
    3297
    3298
    3299
    3300
    3301
    3302
    3303

    def parse(  # type: ignore[override]
        self,
        source: Optional[
            Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
        ],
        publicID: Optional[str] = None,  # noqa: N803
        format: Optional[str] = None,
        **args: Any,
    ) -> NoReturn:
        raise ModificationException()

### `` qname

    qname(uri: str) -> str

Source code in `rdflib/graph.py`

    3265
    3266
    3267
    3268

    def qname(self, uri: str) -> str:
        if hasattr(self, "namespace_manager") and self.namespace_manager:
            return self.namespace_manager.qname(uri)
        raise UnSupportedAggregateOperation()

### `` quads

    quads(triple_or_quad: _TripleOrQuadSelectorType) -> Generator[Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType], None, None]

Iterate over all the quads in the entire aggregate graph

Source code in `rdflib/graph.py`

    3203
    3204
    3205
    3206
    3207
    3208
    3209
    3210
    3211
    3212
    3213
    3214
    3215
    3216
    3217
    3218
    3219
    3220
    3221
    3222
    3223
    3224
    3225
    3226

    def quads(  # type: ignore[override]
        self, triple_or_quad: _TripleOrQuadSelectorType
    ) -> Generator[
        Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType],
        None,
        None,
    ]:
        """Iterate over all the quads in the entire aggregate graph"""
        c = None
        if len(triple_or_quad) == 4:
            # type error: Need more than 3 values to unpack (4 expected)
            s, p, o, c = triple_or_quad  # type: ignore[misc, unused-ignore]
        else:
            # type error: Too many values to unpack (3 expected, 4 provided)
            s, p, o = triple_or_quad  # type: ignore[misc, unused-ignore]

        if c is not None:
            for graph in [g for g in self.graphs if g == c]:
                for s1, p1, o1 in graph.triples((s, p, o)):
                    yield s1, p1, o1, graph
        else:
            for graph in self.graphs:
                for s1, p1, o1 in graph.triples((s, p, o)):
                    yield s1, p1, o1, graph

### `` remove

    remove(triple: _TripleOrOptionalQuadType) -> NoReturn

Source code in `rdflib/graph.py`

    3156
    3157

    def remove(self, triple: _TripleOrOptionalQuadType) -> NoReturn:  # type: ignore[override]
        raise ModificationException()

### `` rollback

    rollback() -> NoReturn

Source code in `rdflib/graph.py`

    3133
    3134

    def rollback(self) -> NoReturn:
        raise ModificationException()

### `` triples

    triples(triple: _TripleSelectorType) -> Generator[_TripleOrTriplePathType, None, None]

Source code in `rdflib/graph.py`

    3178
    3179
    3180
    3181
    3182
    3183
    3184
    3185
    3186
    3187
    3188
    3189

    def triples(
        self,
        triple: _TripleSelectorType,
    ) -> Generator[_TripleOrTriplePathType, None, None]:
        s, p, o = triple
        for graph in self.graphs:
            if isinstance(p, Path):
                for s, o in p.eval(self, s, o):
                    yield s, p, o
            else:
                for s1, p1, o1 in graph.triples((s, p, o)):
                    yield s1, p1, o1

### `` triples_choices

    triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[_TripleType, None, None]

Source code in `rdflib/graph.py`

    3252
    3253
    3254
    3255
    3256
    3257
    3258
    3259
    3260
    3261
    3262
    3263

    def triples_choices(
        self,
        triple: _TripleChoiceType,
        context: Optional[_ContextType] = None,
    ) -> Generator[_TripleType, None, None]:
        subject, predicate, object_ = triple
        for graph in self.graphs:
            # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
            # type error note: unpacking discards type info
            choices = graph.triples_choices((subject, predicate, object_))  # type: ignore[arg-type]
            for s, p, o in choices:
                yield s, p, o

## `` Seq

    Seq(graph: Graph, subject: _SubjectType)

Wrapper around an RDF Seq resource

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

Parameters:

- ### `graph`

  (`Graph`) –

  the graph containing the Seq

- ### `subject`

  (`_SubjectType`) –

  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!

Methods:

- `__getitem__` –

  Item given by index from the Seq

- `__iter__` –

  Generator over the items in the Seq

- `__len__` –

  Length of the Seq

- `toPython` –

Source code in `rdflib/graph.py`

    3051
    3052
    3053
    3054
    3055
    3056
    3057
    3058
    3059
    3060
    3061
    3062
    3063
    3064

    def __init__(self, graph: Graph, subject: _SubjectType):
        self._list: List[Tuple[int, _ObjectType]]
        _list = self._list = list()
        LI_INDEX = URIRef(str(RDF) + "_")  # noqa: N806
        for p, o in graph.predicate_objects(subject):
            # type error: "Node" has no attribute "startswith"
            if p.startswith(LI_INDEX):  # type: ignore[attr-defined] # != RDF.Seq:
                # type error: "Node" has no attribute "replace"
                i = int(p.replace(LI_INDEX, ""))  # type: ignore[attr-defined]
                _list.append((i, o))

        # here is the trick: the predicates are _1, _2, _3, etc. Ie,
        # by sorting the keys (by integer) we have what we want!
        _list.sort()

### `` __getitem__

    __getitem__(index) -> _ObjectType

Item given by index from the Seq

Source code in `rdflib/graph.py`

    3078
    3079
    3080
    3081

    def __getitem__(self, index) -> _ObjectType:
        """Item given by index from the Seq"""
        index, item = self._list.__getitem__(index)
        return item

### `` __iter__

    __iter__() -> Generator[_ObjectType, None, None]

Generator over the items in the Seq

Source code in `rdflib/graph.py`

    3069
    3070
    3071
    3072

    def __iter__(self) -> Generator[_ObjectType, None, None]:
        """Generator over the items in the Seq"""
        for _, item in self._list:
            yield item

### `` __len__

    __len__() -> int

Length of the Seq

Source code in `rdflib/graph.py`

    3074
    3075
    3076

    def __len__(self) -> int:
        """Length of the Seq"""
        return len(self._list)

### `` toPython

    toPython() -> Seq

Source code in `rdflib/graph.py`

    3066
    3067

    def toPython(self) -> Seq:  # noqa: N802
        return self

## `` UnSupportedAggregateOperation

    UnSupportedAggregateOperation()

Bases: `Exception`

Methods:

- `__str__` –

Source code in `rdflib/graph.py`

    3096
    3097

    def __init__(self) -> None:
        pass

### `` __str__

    __str__() -> str

Source code in `rdflib/graph.py`

    3099
    3100

    def __str__(self) -> str:
        return "This operation is not supported by ReadOnlyGraphAggregate " "instances"