src/rdflib/graph.py
1"""
2RDFLib defines the following kinds of Graphs:
3
4* [`Graph`][rdflib.graph.Graph]
5* [`QuotedGraph`][rdflib.graph.QuotedGraph]
6* [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]
7* [`Dataset`][rdflib.graph.Dataset]
8
9## Graph
10
11An RDF graph is a set of RDF triples. Graphs support the python `in`
12operator, as well as iteration and some operations like union,
13difference and intersection.
14
15See [`Graph`][rdflib.graph.Graph]
16
17## Conjunctive Graph
18
19!!! warning "Deprecation notice"
20 `ConjunctiveGraph` is deprecated, use [`Dataset`][rdflib.graph.Dataset] instead.
21
22A Conjunctive Graph is the most relevant collection of graphs that are
23considered to be the boundary for closed world assumptions. This
24boundary is equivalent to that of the store instance (which is itself
25uniquely identified and distinct from other instances of
26[`Store`][rdflib.store.Store] that signify other Conjunctive Graphs). It is
27equivalent to all the named graphs within it and associated with a
28`_default_` graph which is automatically assigned a
29[`BNode`][rdflib.term.BNode] for an identifier - if one isn't given.
30
31See [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]
32
33## Quoted graph
34
35The notion of an RDF graph [14] is extended to include the concept of
36a formula node. A formula node may occur wherever any other kind of
37node can appear. Associated with a formula node is an RDF graph that
38is completely disjoint from all other graphs; i.e. has no nodes in
39common with any other graph. (It may contain the same labels as other
40RDF graphs; because this is, by definition, a separate graph,
41considerations of tidiness do not apply between the graph at a formula
42node and any other graph.)
43
44This is intended to map the idea of "{ N3-expression }" that is used
45by N3 into an RDF graph upon which RDF semantics is defined.
46
47See [`QuotedGraph`][rdflib.graph.QuotedGraph]
48
49## Dataset
50
51The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The
52primary term is "graphs in the datasets" and not "contexts with quads"
53so there is a separate method to set/retrieve a graph in a dataset and
54to operate with dataset graphs. As a consequence of this approach,
55dataset graphs cannot be identified with blank nodes, a name is always
56required (RDFLib will automatically add a name if one is not provided
57at creation time). This implementation includes a convenience method
58to directly add a single quad to a dataset graph.
59
60See [`Dataset`][rdflib.graph.Dataset]
61
62## Working with graphs
63
64Instantiating Graphs with default store (Memory) and default identifier
65(a BNode):
66
67```python
68>>> g = Graph()
69>>> g.store.__class__
70<class 'rdflib.plugins.stores.memory.Memory'>
71>>> g.identifier.__class__
72<class 'rdflib.term.BNode'>
73
74```
75
76Instantiating Graphs with a Memory store and an identifier -
77<https://rdflib.github.io>:
78
79```python
80>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
81>>> g.identifier
82rdflib.term.URIRef('https://rdflib.github.io')
83>>> str(g) # doctest: +NORMALIZE_WHITESPACE
84"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
85 [a rdflib:Store;rdfs:label 'Memory']."
86
87```
88
89Creating a ConjunctiveGraph - The top level container for all named Graphs
90in a "database":
91
92```python
93>>> g = ConjunctiveGraph()
94>>> str(g.default_context)
95"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']]."
96
97```
98
99Adding / removing reified triples to Graph and iterating over it directly or
100via triple pattern:
101
102```python
103>>> g = Graph()
104>>> statementId = BNode()
105>>> print(len(g))
1060
107>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
108<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
109>>> g.add((statementId, RDF.subject,
110... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
111<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
112>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
113<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
114>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) # doctest: +ELLIPSIS
115<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
116>>> print(len(g))
1174
118>>> for s, p, o in g:
119... print(type(s))
120...
121<class 'rdflib.term.BNode'>
122<class 'rdflib.term.BNode'>
123<class 'rdflib.term.BNode'>
124<class 'rdflib.term.BNode'>
125
126>>> for s, p, o in g.triples((None, RDF.object, None)):
127... print(o)
128...
129Conjunctive Graph
130>>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
131<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
132>>> print(len(g))
1333
134
135```
136
137`None` terms in calls to [`triples()`][rdflib.graph.Graph.triples] can be
138thought of as "open variables".
139
140Graph support set-theoretic operators, you can add/subtract graphs, as
141well as intersection (with multiplication operator g1*g2) and xor (g1
142^ g2).
143
144Note that BNode IDs are kept when doing set-theoretic operations, this
145may or may not be what you want. Two named graphs within the same
146application probably want share BNode IDs, two graphs with data from
147different sources probably not. If your BNode IDs are all generated
148by RDFLib they are UUIDs and unique.
149
150```python
151>>> g1 = Graph()
152>>> g2 = Graph()
153>>> u = URIRef("http://example.com/foo")
154>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
155<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
156>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS
157<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
158>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
159<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
160>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) # doctest: +ELLIPSIS
161<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
162>>> len(g1 + g2) # adds bing as label
1633
164>>> len(g1 - g2) # removes foo
1651
166>>> len(g1 * g2) # only foo
1671
168>>> g1 += g2 # now g1 contains everything
169
170```
171
172Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within
173the same store:
174
175```python
176>>> store = plugin.get("Memory", Store)()
177>>> g1 = Graph(store)
178>>> g2 = Graph(store)
179>>> g3 = Graph(store)
180>>> stmt1 = BNode()
181>>> stmt2 = BNode()
182>>> stmt3 = BNode()
183>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
184<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
185>>> g1.add((stmt1, RDF.subject,
186... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
187<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
188>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
189<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
190>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS
191<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
192>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
193<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
194>>> g2.add((stmt2, RDF.subject,
195... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
196<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
197>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
198<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
199>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS
200<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
201>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
202<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
203>>> g3.add((stmt3, RDF.subject,
204... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
205<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
206>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
207<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
208>>> g3.add((stmt3, RDF.object, Literal(
209... 'The top-level aggregate graph - The sum ' +
210... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS
211<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
212>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
2133
214>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
215... RDF.type, RDF.Statement)))
2162
217
218```
219
220ConjunctiveGraphs have a [`quads()`][rdflib.graph.ConjunctiveGraph.quads] method
221which returns quads instead of triples, where the fourth item is the Graph
222(or subclass thereof) instance in which the triple was asserted:
223
224```python
225>>> uniqueGraphNames = set(
226... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
227... ).quads((None, RDF.predicate, None))])
228>>> len(uniqueGraphNames)
2293
230>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
231>>> uniqueGraphNames = set(
232... [graph.identifier for s, p, o, graph in unionGraph.quads(
233... (None, RDF.predicate, None))])
234>>> len(uniqueGraphNames)
2352
236
237```
238
239Parsing N3 from a string:
240
241```python
242>>> g2 = Graph()
243>>> src = '''
244... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
245... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
246... [ a rdf:Statement ;
247... rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
248... rdf:predicate rdfs:label;
249... rdf:object "Conjunctive Graph" ] .
250... '''
251>>> g2 = g2.parse(data=src, format="n3")
252>>> print(len(g2))
2534
254
255```
256
257Using Namespace class:
258
259```python
260>>> RDFLib = Namespace("https://rdflib.github.io/")
261>>> RDFLib.ConjunctiveGraph
262rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
263>>> RDFLib["Graph"]
264rdflib.term.URIRef('https://rdflib.github.io/Graph')
265
266```
267"""
268
269from __future__ import annotations
270
271import logging
272import pathlib
273import random
274import warnings
275from io import BytesIO
276from typing import (
277 IO,
278 TYPE_CHECKING,
279 Any,
280 BinaryIO,
281 Callable,
282 Dict,
283 Generator,
284 Iterable,
285 List,
286 Mapping,
287 NoReturn,
288 Optional,
289 Set,
290 TextIO,
291 Tuple,
292 Type,
293 TypeVar,
294 Union,
295 cast,
296 overload,
297)
298from urllib.parse import urlparse
299from urllib.request import url2pathname
300
301import rdflib.exceptions as exceptions
302import rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.
303import rdflib.plugin as plugin
304import rdflib.query as query
305import rdflib.util # avoid circular dependency
306from rdflib.collection import Collection
307from rdflib.exceptions import ParserError
308from rdflib.namespace import RDF, Namespace, NamespaceManager
309from rdflib.parser import InputSource, Parser, create_input_source
310from rdflib.paths import Path
311from rdflib.resource import Resource
312from rdflib.serializer import Serializer
313from rdflib.store import Store
314from rdflib.term import (
315 BNode,
316 Genid,
317 IdentifiedNode,
318 Identifier,
319 Literal,
320 Node,
321 RDFLibGenid,
322 URIRef,
323)
324
325if TYPE_CHECKING:
326 import typing_extensions as te
327
328 import rdflib.query
329 from rdflib.plugins.sparql.sparql import Query, Update
330
331_SubjectType = Node
332_PredicateType = Node
333_ObjectType = Node
334_ContextIdentifierType = IdentifiedNode
335
336_TripleType = Tuple["_SubjectType", "_PredicateType", "_ObjectType"]
337_QuadType = Tuple["_SubjectType", "_PredicateType", "_ObjectType", "_ContextType"]
338_OptionalQuadType = Tuple[
339 "_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextType"]
340]
341_TripleOrOptionalQuadType = Union["_TripleType", "_OptionalQuadType"]
342_OptionalIdentifiedQuadType = Tuple[
343 "_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextIdentifierType"]
344]
345_TriplePatternType = Tuple[
346 Optional["_SubjectType"], Optional["_PredicateType"], Optional["_ObjectType"]
347]
348_TriplePathPatternType = Tuple[Optional["_SubjectType"], Path, Optional["_ObjectType"]]
349_QuadPatternType = Tuple[
350 Optional["_SubjectType"],
351 Optional["_PredicateType"],
352 Optional["_ObjectType"],
353 Optional["_ContextType"],
354]
355_QuadPathPatternType = Tuple[
356 Optional["_SubjectType"],
357 Path,
358 Optional["_ObjectType"],
359 Optional["_ContextType"],
360]
361_TripleOrQuadPatternType = Union["_TriplePatternType", "_QuadPatternType"]
362_TripleOrQuadPathPatternType = Union["_TriplePathPatternType", "_QuadPathPatternType"]
363_TripleSelectorType = Tuple[
364 Optional["_SubjectType"],
365 Optional[Union["Path", "_PredicateType"]],
366 Optional["_ObjectType"],
367]
368_QuadSelectorType = Tuple[
369 Optional["_SubjectType"],
370 Optional[Union["Path", "_PredicateType"]],
371 Optional["_ObjectType"],
372 Optional["_ContextType"],
373]
374_TripleOrQuadSelectorType = Union["_TripleSelectorType", "_QuadSelectorType"]
375_TriplePathType = Tuple["_SubjectType", Path, "_ObjectType"]
376_TripleOrTriplePathType = Union["_TripleType", "_TriplePathType"]
377_TripleChoiceType = Union[
378 Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]],
379 Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]],
380 Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]],
381]
382
383_GraphT = TypeVar("_GraphT", bound="Graph")
384_ConjunctiveGraphT = TypeVar("_ConjunctiveGraphT", bound="ConjunctiveGraph")
385_DatasetT = TypeVar("_DatasetT", bound="Dataset")
386
387# type error: Function "Type[Literal]" could always be true in boolean contex
388assert Literal # type: ignore[truthy-function] # avoid warning
389# type error: Function "Type[Namespace]" could always be true in boolean context
390assert Namespace # type: ignore[truthy-function] # avoid warning
391
392if TYPE_CHECKING:
393 from rdflib._type_checking import _NamespaceSetString
394
395logger = logging.getLogger(__name__)
396
397
398__all__ = [
399 "Graph",
400 "ConjunctiveGraph",
401 "QuotedGraph",
402 "Seq",
403 "ModificationException",
404 "Dataset",
405 "UnSupportedAggregateOperation",
406 "ReadOnlyGraphAggregate",
407 "BatchAddGraph",
408 "_ConjunctiveGraphT",
409 "_ContextIdentifierType",
410 "_DatasetT",
411 "_GraphT",
412 "_ObjectType",
413 "_OptionalIdentifiedQuadType",
414 "_OptionalQuadType",
415 "_PredicateType",
416 "_QuadPathPatternType",
417 "_QuadPatternType",
418 "_QuadSelectorType",
419 "_QuadType",
420 "_SubjectType",
421 "_TripleOrOptionalQuadType",
422 "_TripleOrTriplePathType",
423 "_TripleOrQuadPathPatternType",
424 "_TripleOrQuadPatternType",
425 "_TripleOrQuadSelectorType",
426 "_TriplePathPatternType",
427 "_TriplePathType",
428 "_TriplePatternType",
429 "_TripleSelectorType",
430 "_TripleType",
431]
432
433# : Transitive closure arg type.
434_TCArgT = TypeVar("_TCArgT")
435
436
437# Graph is a node because technically a formula-aware graph
438# take a Graph as subject or object, but we usually use QuotedGraph for that.
439class Graph(Node):
440 """An RDF Graph: a Python object containing nodes and relations between them as
441 RDF 'triples'.
442
443 This is the central RDFLib object class and Graph objects are almost always present
444 in all uses of RDFLib.
445
446 Example:
447 The basic use is to create a Graph and iterate through or query its content:
448
449 ```python
450 >>> from rdflib import Graph, URIRef
451 >>> g = Graph()
452 >>> g.add((
453 ... URIRef("http://example.com/s1"), # subject
454 ... URIRef("http://example.com/p1"), # predicate
455 ... URIRef("http://example.com/o1"), # object
456 ... )) # doctest: +ELLIPSIS
457 <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
458
459 >>> g.add((
460 ... URIRef("http://example.com/s2"), # subject
461 ... URIRef("http://example.com/p2"), # predicate
462 ... URIRef("http://example.com/o2"), # object
463 ... )) # doctest: +ELLIPSIS
464 <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
465
466 >>> for triple in sorted(g): # simple looping
467 ... print(triple)
468 (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))
469 (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))
470
471 >>> # get the object of the triple with subject s1 and predicate p1
472 >>> o = g.value(
473 ... subject=URIRef("http://example.com/s1"),
474 ... predicate=URIRef("http://example.com/p1")
475 ... )
476
477 ```
478
479
480 Args:
481 store: The constructor accepts one argument, the "store" that will be used to store the
482 graph data with the default being the [`Memory`][rdflib.plugins.stores.memory.Memory]
483 (in memory) Store. Other Stores that persist content to disk using various file
484 databases or Stores that use remote servers (SPARQL systems) are supported.
485 All [builtin storetypes][rdflib.plugins.stores] can be accessed via
486 their registered names.
487 Other Stores not shipped with RDFLib can be added as plugins, such as
488 [HDT](https://github.com/rdflib/rdflib-hdt/).
489 Registration of external plugins
490 is described in [`rdflib.plugin`][rdflib.plugin].
491
492 Stores can be context-aware or unaware. Unaware stores take up
493 (some) less space but cannot support features that require
494 context, such as true merging/demerging of sub-graphs and
495 provenance.
496
497 Even if used with a context-aware store, Graph will only expose the quads which
498 belong to the default graph. To access the rest of the data the
499 `Dataset` class can be used instead.
500
501 The Graph constructor can take an identifier which identifies the Graph
502 by name. If none is given, the graph is assigned a BNode for its
503 identifier.
504
505 For more on Named Graphs, see the RDFLib `Dataset` class and the TriG Specification,
506 <https://www.w3.org/TR/trig/>.
507 identifier: identifier of the graph itself
508 namespace_manager: Used namespace manager.
509 Create with bind_namespaces if `None`.
510 base: Base used for [URIs][rdflib.term.URIRef]
511 bind_namespaces: Used bind_namespaces for namespace_manager
512 Is only used, when no namespace_manager is provided.
513 """
514
515 context_aware: bool
516 formula_aware: bool
517 default_union: bool
518 base: Optional[str]
519
520 def __init__(
521 self,
522 store: Union[Store, str] = "default",
523 identifier: Optional[Union[_ContextIdentifierType, str]] = None,
524 namespace_manager: Optional[NamespaceManager] = None,
525 base: Optional[str] = None,
526 bind_namespaces: _NamespaceSetString = "rdflib",
527 ):
528 super(Graph, self).__init__()
529 self.base = base
530 self.__identifier: _ContextIdentifierType
531 self.__identifier = identifier or BNode() # type: ignore[assignment]
532 if not isinstance(self.__identifier, IdentifiedNode):
533 self.__identifier = URIRef(self.__identifier) # type: ignore[unreachable]
534 self.__store: Store
535 if not isinstance(store, Store):
536 # TODO: error handling
537 self.__store = store = plugin.get(store, Store)()
538 else:
539 self.__store = store
540 self.__namespace_manager = namespace_manager
541 self._bind_namespaces = bind_namespaces
542 self.context_aware = False
543 self.formula_aware = False
544 self.default_union = False
545
546 @property
547 def store(self) -> Store:
548 return self.__store
549
550 @property
551 def identifier(self) -> _ContextIdentifierType:
552 return self.__identifier
553
554 @property
555 def namespace_manager(self) -> NamespaceManager:
556 """
557 this graph's namespace-manager
558 """
559 if self.__namespace_manager is None:
560 self.__namespace_manager = NamespaceManager(self, self._bind_namespaces)
561 return self.__namespace_manager
562
563 @namespace_manager.setter
564 def namespace_manager(self, nm: NamespaceManager) -> None:
565 self.__namespace_manager = nm
566
567 def __repr__(self) -> str:
568 return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
569
570 def __str__(self) -> str:
571 if isinstance(self.identifier, URIRef):
572 return (
573 "%s a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']."
574 ) % (self.identifier.n3(), self.store.__class__.__name__)
575 else:
576 return (
577 "[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]."
578 ) % self.store.__class__.__name__
579
580 def toPython(self: _GraphT) -> _GraphT: # noqa: N802
581 return self
582
583 def destroy(self: _GraphT, configuration: str) -> _GraphT:
584 """Destroy the store identified by `configuration` if supported"""
585 self.__store.destroy(configuration)
586 return self
587
588 # Transactional interfaces (optional)
589 def commit(self: _GraphT) -> _GraphT:
590 """Commits active transactions"""
591 self.__store.commit()
592 return self
593
594 def rollback(self: _GraphT) -> _GraphT:
595 """Rollback active transactions"""
596 self.__store.rollback()
597 return self
598
599 def open(
600 self, configuration: Union[str, tuple[str, str]], create: bool = False
601 ) -> Optional[int]:
602 """Open the graph store
603
604 Might be necessary for stores that require opening a connection to a
605 database or acquiring some resource.
606 """
607 return self.__store.open(configuration, create)
608
609 def close(self, commit_pending_transaction: bool = False) -> None:
610 """Close the graph store
611
612 Might be necessary for stores that require closing a connection to a
613 database or releasing some resource.
614 """
615 return self.__store.close(commit_pending_transaction=commit_pending_transaction)
616
617 def add(self: _GraphT, triple: _TripleType) -> _GraphT:
618 """Add a triple with self as context.
619
620 Args:
621 triple: The triple to add to the graph.
622
623 Returns:
624 The graph instance.
625 """
626 s, p, o = triple
627 assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,)
628 assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,)
629 assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,)
630 self.__store.add((s, p, o), self, quoted=False)
631 return self
632
633 def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT: # noqa: N802
634 """Add a sequence of triple with context"""
635
636 self.__store.addN(
637 (s, p, o, c)
638 for s, p, o, c in quads
639 if isinstance(c, Graph)
640 and c.identifier is self.identifier
641 and _assertnode(s, p, o)
642 )
643 return self
644
645 def remove(self: _GraphT, triple: _TriplePatternType) -> _GraphT:
646 """Remove a triple from the graph
647
648 If the triple does not provide a context attribute, removes the triple
649 from all contexts.
650 """
651 self.__store.remove(triple, context=self)
652 return self
653
654 @overload
655 def triples(
656 self,
657 triple: _TriplePatternType,
658 ) -> Generator[_TripleType, None, None]: ...
659
660 @overload
661 def triples(
662 self,
663 triple: _TriplePathPatternType,
664 ) -> Generator[_TriplePathType, None, None]: ...
665
666 @overload
667 def triples(
668 self,
669 triple: _TripleSelectorType,
670 ) -> Generator[_TripleOrTriplePathType, None, None]: ...
671
672 def triples(
673 self,
674 triple: _TripleSelectorType,
675 ) -> Generator[_TripleOrTriplePathType, None, None]:
676 """Generator over the triple store.
677
678 Returns triples that match the given triple pattern. If the triple pattern
679 does not provide a context, all contexts will be searched.
680
681 Args:
682 triple: A triple pattern where each component can be a specific value or None
683 as a wildcard. The predicate can also be a path expression.
684
685 Yields:
686 Triples matching the given pattern.
687 """
688 s, p, o = triple
689 if isinstance(p, Path):
690 for _s, _o in p.eval(self, s, o):
691 yield _s, p, _o
692 else:
693 for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self):
694 yield _s, _p, _o
695
696 def __getitem__(self, item):
697 """
698 A graph can be "sliced" as a shortcut for the triples method
699 The python slice syntax is (ab)used for specifying triples.
700 A generator over matches is returned,
701 the returned tuples include only the parts not given
702
703 ```python
704 >>> import rdflib
705 >>> g = rdflib.Graph()
706 >>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
707 <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
708
709 >>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
710 [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]
711
712 >>> list(g[:namespace.RDFS.label]) # all label triples
713 [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]
714
715 >>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
716 [(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]
717
718 ```
719
720 Combined with SPARQL paths, more complex queries can be
721 written concisely:
722
723 - Name of all Bobs friends: `g[bob : FOAF.knows/FOAF.name ]`
724 - Some label for Bob: `g[bob : DC.title|FOAF.name|RDFS.label]`
725 - All friends and friends of friends of Bob: `g[bob : FOAF.knows * "+"]`
726 - etc.
727
728 !!! example "New in version 4.0"
729 """
730
731 if isinstance(item, slice):
732 s, p, o = item.start, item.stop, item.step
733 if s is None and p is None and o is None:
734 return self.triples((s, p, o))
735 elif s is None and p is None:
736 # type error: Argument 1 to "subject_predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
737 return self.subject_predicates(o) # type: ignore[arg-type]
738 elif s is None and o is None:
739 # type error: Argument 1 to "subject_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
740 return self.subject_objects(p) # type: ignore[arg-type]
741 elif p is None and o is None:
742 # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
743 return self.predicate_objects(s) # type: ignore[arg-type]
744 elif s is None:
745 # type error: Argument 1 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
746 # Argument 2 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]"
747 return self.subjects(p, o) # type: ignore[arg-type]
748 elif p is None:
749 # type error: Argument 1 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
750 # Argument 2 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]"
751 return self.predicates(s, o) # type: ignore[arg-type]
752 elif o is None:
753 # type error: Argument 1 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]"
754 # Argument 2 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]"
755 return self.objects(s, p) # type: ignore[arg-type]
756 else:
757 # type error: Unsupported operand types for in ("Tuple[Union[int, Any], Union[int, Any], Union[int, Any]]" and "Graph")
758 # all given
759 return (s, p, o) in self # type: ignore[operator]
760
761 elif isinstance(item, (Path, Node)):
762 # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[Path, Node]"; expected "Optional[Node]"
763 return self.predicate_objects(item) # type: ignore[arg-type]
764
765 else:
766 raise TypeError(
767 "You can only index a graph by a single rdflib term or path, or a slice of rdflib terms."
768 )
769
770 def __len__(self) -> int:
771 """Returns the number of triples in the graph.
772
773 If context is specified then the number of triples in the context is
774 returned instead.
775
776 Returns:
777 The number of triples in the graph.
778 """
779 # type error: Unexpected keyword argument "context" for "__len__" of "Store"
780 return self.__store.__len__(context=self) # type: ignore[call-arg]
781
782 def __iter__(self) -> Generator[_TripleType, None, None]:
783 """Iterates over all triples in the store.
784
785 Returns:
786 A generator yielding all triples in the store.
787 """
788 return self.triples((None, None, None))
789
790 def __contains__(self, triple: _TripleSelectorType) -> bool:
791 """Support for 'triple in graph' syntax.
792
793 Args:
794 triple: The triple pattern to check for.
795
796 Returns:
797 True if the triple pattern exists in the graph, False otherwise.
798 """
799 for triple in self.triples(triple):
800 return True
801 return False
802
803 def __hash__(self) -> int:
804 return hash(self.identifier)
805
806 def __cmp__(self, other) -> int:
807 if other is None:
808 return -1
809 elif isinstance(other, Graph):
810 return (self.identifier > other.identifier) - (
811 self.identifier < other.identifier
812 )
813 else:
814 # Note if None is considered equivalent to owl:Nothing
815 # Then perhaps a graph with length 0 should be considered
816 # equivalent to None (if compared to it)?
817 return 1
818
819 def __eq__(self, other) -> bool:
820 return isinstance(other, Graph) and self.identifier == other.identifier
821
822 def __lt__(self, other) -> bool:
823 return (other is None) or (
824 isinstance(other, Graph) and self.identifier < other.identifier
825 )
826
827 def __le__(self, other: Graph) -> bool:
828 return self < other or self == other
829
830 def __gt__(self, other) -> bool:
831 return (isinstance(other, Graph) and self.identifier > other.identifier) or (
832 other is not None
833 )
834
835 def __ge__(self, other: Graph) -> bool:
836 return self > other or self == other
837
838 def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT:
839 """Add all triples in Graph other to Graph.
840 BNode IDs are not changed."""
841 self.addN((s, p, o, self) for s, p, o in other)
842 return self
843
844 def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT:
845 """Subtract all triples in Graph other from Graph.
846 BNode IDs are not changed."""
847 for triple in other:
848 self.remove(triple)
849 return self
850
851 def __add__(self, other: Graph) -> Graph:
852 """Set-theoretic union
853 BNode IDs are not changed."""
854 try:
855 retval = type(self)()
856 except TypeError:
857 retval = Graph()
858 for prefix, uri in set(list(self.namespaces()) + list(other.namespaces())):
859 retval.bind(prefix, uri)
860 for x in self:
861 retval.add(x)
862 for y in other:
863 retval.add(y)
864 return retval
865
866 def __mul__(self, other: Graph) -> Graph:
867 """Set-theoretic intersection.
868 BNode IDs are not changed."""
869 try:
870 retval = type(self)()
871 except TypeError:
872 retval = Graph()
873 for x in other:
874 if x in self:
875 retval.add(x)
876 return retval
877
878 def __sub__(self, other: Graph) -> Graph:
879 """Set-theoretic difference.
880 BNode IDs are not changed."""
881 try:
882 retval = type(self)()
883 except TypeError:
884 retval = Graph()
885 for x in self:
886 if x not in other:
887 retval.add(x)
888 return retval
889
890 def __xor__(self, other: Graph) -> Graph:
891 """Set-theoretic XOR.
892 BNode IDs are not changed."""
893 return (self - other) + (other - self)
894
895 __or__ = __add__
896 __and__ = __mul__
897
898 # Conv. methods
899
900 def set(
901 self: _GraphT, triple: Tuple[_SubjectType, _PredicateType, _ObjectType]
902 ) -> _GraphT:
903 """Convenience method to update the value of object
904
905 Remove any existing triples for subject and predicate before adding
906 (subject, predicate, object).
907 """
908 (subject, predicate, object_) = triple
909 assert (
910 subject is not None
911 ), "s can't be None in .set([s,p,o]), as it would remove (*, p, *)"
912 assert (
913 predicate is not None
914 ), "p can't be None in .set([s,p,o]), as it would remove (s, *, *)"
915 self.remove((subject, predicate, None))
916 self.add((subject, predicate, object_))
917 return self
918
919 def subjects(
920 self,
921 predicate: Union[None, Path, _PredicateType] = None,
922 object: Optional[Union[_ObjectType, List[_ObjectType]]] = None,
923 unique: bool = False,
924 ) -> Generator[_SubjectType, None, None]:
925 """A generator of (optionally unique) subjects with the given
926 predicate and object(s)
927
928 Args:
929 predicate: A specific predicate to match or None to match any predicate.
930 object: A specific object or list of objects to match or None to match any object.
931 unique: If True, only yield unique subjects.
932 """
933 # if the object is a list of Nodes, yield results from subject() call for each
934 if isinstance(object, list):
935 for obj in object:
936 for s in self.subjects(predicate, obj, unique):
937 yield s
938 else:
939 if not unique:
940 for s, p, o in self.triples((None, predicate, object)):
941 yield s
942 else:
943 subs = set()
944 for s, p, o in self.triples((None, predicate, object)):
945 if s not in subs:
946 yield s
947 try:
948 subs.add(s)
949 except MemoryError as e:
950 logger.error(
951 f"{e}. Consider not setting parameter 'unique' to True"
952 )
953 raise
954
955 def predicates(
956 self,
957 subject: Optional[_SubjectType] = None,
958 object: Optional[_ObjectType] = None,
959 unique: bool = False,
960 ) -> Generator[_PredicateType, None, None]:
961 """Generate predicates with the given subject and object.
962
963 Args:
964 subject: A specific subject to match or None to match any subject.
965 object: A specific object to match or None to match any object.
966 unique: If True, only yield unique predicates.
967
968 Yields:
969 Predicates matching the given subject and object.
970 """
971 if not unique:
972 for s, p, o in self.triples((subject, None, object)):
973 yield p
974 else:
975 preds = set()
976 for s, p, o in self.triples((subject, None, object)):
977 if p not in preds:
978 yield p
979 try:
980 preds.add(p)
981 except MemoryError as e:
982 logger.error(
983 f"{e}. Consider not setting parameter 'unique' to True"
984 )
985 raise
986
987 def objects(
988 self,
989 subject: Optional[Union[_SubjectType, List[_SubjectType]]] = None,
990 predicate: Union[None, Path, _PredicateType] = None,
991 unique: bool = False,
992 ) -> Generator[_ObjectType, None, None]:
993 """A generator of (optionally unique) objects with the given
994 subject(s) and predicate
995
996 Args:
997 subject: A specific subject or a list of subjects to match or None to match any subject.
998 predicate: A specific predicate to match or None to match any predicate.
999 unique: If True, only yield unique objects.
1000
1001 Yields:
1002 Objects matching the given subject and predicate.
1003 """
1004 if isinstance(subject, list):
1005 for subj in subject:
1006 for o in self.objects(subj, predicate, unique):
1007 yield o
1008 else:
1009 if not unique:
1010 for s, p, o in self.triples((subject, predicate, None)):
1011 yield o
1012 else:
1013 objs = set()
1014 for s, p, o in self.triples((subject, predicate, None)):
1015 if o not in objs:
1016 yield o
1017 try:
1018 objs.add(o)
1019 except MemoryError as e:
1020 logger.error(
1021 f"{e}. Consider not setting parameter 'unique' to True"
1022 )
1023 raise
1024
1025 def subject_predicates(
1026 self, object: Optional[_ObjectType] = None, unique: bool = False
1027 ) -> Generator[Tuple[_SubjectType, _PredicateType], None, None]:
1028 """A generator of (optionally unique) (subject, predicate) tuples
1029 for the given object"""
1030 if not unique:
1031 for s, p, o in self.triples((None, None, object)):
1032 yield s, p
1033 else:
1034 subj_preds = set()
1035 for s, p, o in self.triples((None, None, object)):
1036 if (s, p) not in subj_preds:
1037 yield s, p
1038 try:
1039 subj_preds.add((s, p))
1040 except MemoryError as e:
1041 logger.error(
1042 f"{e}. Consider not setting parameter 'unique' to True"
1043 )
1044 raise
1045
1046 def subject_objects(
1047 self,
1048 predicate: Union[None, Path, _PredicateType] = None,
1049 unique: bool = False,
1050 ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]:
1051 """A generator of (optionally unique) (subject, object) tuples
1052 for the given predicate"""
1053 if not unique:
1054 for s, p, o in self.triples((None, predicate, None)):
1055 yield s, o
1056 else:
1057 subj_objs = set()
1058 for s, p, o in self.triples((None, predicate, None)):
1059 if (s, o) not in subj_objs:
1060 yield s, o
1061 try:
1062 subj_objs.add((s, o))
1063 except MemoryError as e:
1064 logger.error(
1065 f"{e}. Consider not setting parameter 'unique' to True"
1066 )
1067 raise
1068
1069 def predicate_objects(
1070 self, subject: Optional[_SubjectType] = None, unique: bool = False
1071 ) -> Generator[Tuple[_PredicateType, _ObjectType], None, None]:
1072 """A generator of (optionally unique) (predicate, object) tuples
1073 for the given subject"""
1074 if not unique:
1075 for s, p, o in self.triples((subject, None, None)):
1076 yield p, o
1077 else:
1078 pred_objs = set()
1079 for s, p, o in self.triples((subject, None, None)):
1080 if (p, o) not in pred_objs:
1081 yield p, o
1082 try:
1083 pred_objs.add((p, o))
1084 except MemoryError as e:
1085 logger.error(
1086 f"{e}. Consider not setting parameter 'unique' to True"
1087 )
1088 raise
1089
1090 def triples_choices(
1091 self,
1092 triple: _TripleChoiceType,
1093 context: Optional[_ContextType] = None,
1094 ) -> Generator[_TripleType, None, None]:
1095 subject, predicate, object_ = triple
1096 # 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]]]"
1097 # type error note: unpacking discards type info
1098 for (s, p, o), cg in self.store.triples_choices(
1099 (subject, predicate, object_), context=self # type: ignore[arg-type]
1100 ):
1101 yield s, p, o
1102
1103 @overload
1104 def value(
1105 self,
1106 subject: None = ...,
1107 predicate: None = ...,
1108 object: Optional[_ObjectType] = ...,
1109 default: Optional[Node] = ...,
1110 any: bool = ...,
1111 ) -> None: ...
1112
1113 @overload
1114 def value(
1115 self,
1116 subject: Optional[_SubjectType] = ...,
1117 predicate: None = ...,
1118 object: None = ...,
1119 default: Optional[Node] = ...,
1120 any: bool = ...,
1121 ) -> None: ...
1122
1123 @overload
1124 def value(
1125 self,
1126 subject: None = ...,
1127 predicate: Optional[_PredicateType] = ...,
1128 object: None = ...,
1129 default: Optional[Node] = ...,
1130 any: bool = ...,
1131 ) -> None: ...
1132
1133 @overload
1134 def value(
1135 self,
1136 subject: Optional[_SubjectType] = ...,
1137 predicate: Optional[_PredicateType] = ...,
1138 object: Optional[_ObjectType] = ...,
1139 default: Optional[Node] = ...,
1140 any: bool = ...,
1141 ) -> Optional[Node]: ...
1142
1143 def value(
1144 self,
1145 subject: Optional[_SubjectType] = None,
1146 predicate: Optional[_PredicateType] = RDF.value,
1147 object: Optional[_ObjectType] = None,
1148 default: Optional[Node] = None,
1149 any: bool = True,
1150 ) -> Optional[Node]:
1151 """Get a value for a pair of two criteria
1152
1153 Exactly one of subject, predicate, object must be None. Useful if one
1154 knows that there may only be one value.
1155
1156 It is one of those situations that occur a lot, hence this
1157 'macro' like utility
1158
1159 Args:
1160 subject: Subject of the triple pattern, exactly one of subject, predicate, object must be None
1161 predicate: Predicate of the triple pattern, exactly one of subject, predicate, object must be None
1162 object: Object of the triple pattern, exactly one of subject, predicate, object must be None
1163 default: Value to be returned if no values found
1164 any: If True, return any value in the case there is more than one, else, raise UniquenessError
1165 """
1166 retval = default
1167
1168 if (
1169 (subject is None and predicate is None)
1170 or (subject is None and object is None)
1171 or (predicate is None and object is None)
1172 ):
1173 return None
1174
1175 if object is None:
1176 values = self.objects(subject, predicate)
1177 if subject is None:
1178 values = self.subjects(predicate, object)
1179 if predicate is None:
1180 values = self.predicates(subject, object)
1181
1182 try:
1183 retval = next(values)
1184 except StopIteration:
1185 retval = default
1186 else:
1187 if any is False:
1188 try:
1189 next(values)
1190 msg = (
1191 "While trying to find a value for (%s, %s, %s) the"
1192 " following multiple values where found:\n"
1193 % (subject, predicate, object)
1194 )
1195 triples = self.store.triples((subject, predicate, object), None)
1196 for (s, p, o), contexts in triples:
1197 msg += "(%s, %s, %s)\n (contexts: %s)\n" % (
1198 s,
1199 p,
1200 o,
1201 list(contexts),
1202 )
1203 raise exceptions.UniquenessError(msg)
1204 except StopIteration:
1205 pass
1206 return retval
1207
1208 def items(self, list: Node) -> Generator[Node, None, None]:
1209 """Generator over all items in the resource specified by list
1210
1211 Args:
1212 list: An RDF collection.
1213 """
1214 chain = set([list])
1215 while list:
1216 item = self.value(list, RDF.first)
1217 if item is not None:
1218 yield item
1219 # type error: Incompatible types in assignment (expression has type "Optional[Node]", variable has type "Node")
1220 list = self.value(list, RDF.rest) # type: ignore[assignment]
1221 if list in chain:
1222 raise ValueError("List contains a recursive rdf:rest reference")
1223 chain.add(list)
1224
1225 def transitiveClosure( # noqa: N802
1226 self,
1227 func: Callable[[_TCArgT, Graph], Iterable[_TCArgT]],
1228 arg: _TCArgT,
1229 seen: Optional[Dict[_TCArgT, int]] = None,
1230 ):
1231 """Generates transitive closure of a user-defined function against the graph
1232
1233 ```python
1234 from rdflib.collection import Collection
1235 g = Graph()
1236 a = BNode("foo")
1237 b = BNode("bar")
1238 c = BNode("baz")
1239 g.add((a,RDF.first,RDF.type))
1240 g.add((a,RDF.rest,b))
1241 g.add((b,RDF.first,namespace.RDFS.label))
1242 g.add((b,RDF.rest,c))
1243 g.add((c,RDF.first,namespace.RDFS.comment))
1244 g.add((c,RDF.rest,RDF.nil))
1245 def topList(node,g):
1246 for s in g.subjects(RDF.rest, node):
1247 yield s
1248 def reverseList(node,g):
1249 for f in g.objects(node, RDF.first):
1250 print(f)
1251 for s in g.subjects(RDF.rest, node):
1252 yield s
1253
1254 [rt for rt in g.transitiveClosure(
1255 topList,RDF.nil)]
1256 # [rdflib.term.BNode('baz'),
1257 # rdflib.term.BNode('bar'),
1258 # rdflib.term.BNode('foo')]
1259
1260 [rt for rt in g.transitiveClosure(
1261 reverseList,RDF.nil)]
1262 # http://www.w3.org/2000/01/rdf-schema#comment
1263 # http://www.w3.org/2000/01/rdf-schema#label
1264 # http://www.w3.org/1999/02/22-rdf-syntax-ns#type
1265 # [rdflib.term.BNode('baz'),
1266 # rdflib.term.BNode('bar'),
1267 # rdflib.term.BNode('foo')]
1268 ```
1269
1270 Args:
1271 func: A function that generates a sequence of nodes
1272 arg: The starting node
1273 seen: A dict of visited nodes
1274 """
1275 if seen is None:
1276 seen = {}
1277 elif arg in seen:
1278 return
1279 seen[arg] = 1
1280 for rt in func(arg, self):
1281 yield rt
1282 for rt_2 in self.transitiveClosure(func, rt, seen):
1283 yield rt_2
1284
1285 def transitive_objects(
1286 self,
1287 subject: Optional[_SubjectType],
1288 predicate: Optional[_PredicateType],
1289 remember: Optional[Dict[Optional[_SubjectType], int]] = None,
1290 ) -> Generator[Optional[_SubjectType], None, None]:
1291 """Transitively generate objects for the ``predicate`` relationship
1292
1293 Generated objects belong to the depth first transitive closure of the
1294 `predicate` relationship starting at `subject`.
1295
1296 Args:
1297 subject: The subject to start the transitive closure from
1298 predicate: The predicate to follow
1299 remember: A dict of visited nodes
1300 """
1301 if remember is None:
1302 remember = {}
1303 if subject in remember:
1304 return
1305 remember[subject] = 1
1306 yield subject
1307 for object in self.objects(subject, predicate):
1308 for o in self.transitive_objects(object, predicate, remember):
1309 yield o
1310
1311 def transitive_subjects(
1312 self,
1313 predicate: Optional[_PredicateType],
1314 object: Optional[_ObjectType],
1315 remember: Optional[Dict[Optional[_ObjectType], int]] = None,
1316 ) -> Generator[Optional[_ObjectType], None, None]:
1317 """Transitively generate subjects for the ``predicate`` relationship
1318
1319 Generated subjects belong to the depth first transitive closure of the
1320 `predicate` relationship starting at `object`.
1321
1322 Args:
1323 predicate: The predicate to follow
1324 object: The object to start the transitive closure from
1325 remember: A dict of visited nodes
1326 """
1327 if remember is None:
1328 remember = {}
1329 if object in remember:
1330 return
1331 remember[object] = 1
1332 yield object
1333 for subject in self.subjects(predicate, object):
1334 for s in self.transitive_subjects(predicate, subject, remember):
1335 yield s
1336
1337 def qname(self, uri: str) -> str:
1338 return self.namespace_manager.qname(uri)
1339
1340 def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
1341 return self.namespace_manager.compute_qname(uri, generate)
1342
1343 def bind(
1344 self,
1345 prefix: Optional[str],
1346 namespace: Any, # noqa: F811
1347 override: bool = True,
1348 replace: bool = False,
1349 ) -> None:
1350 """Bind prefix to namespace
1351
1352 If override is True will bind namespace to given prefix even
1353 if namespace was already bound to a different prefix.
1354
1355 if replace, replace any existing prefix with the new namespace
1356
1357 Args:
1358 prefix: The prefix to bind
1359 namespace: The namespace to bind the prefix to
1360 override: If True, override any existing prefix binding
1361 replace: If True, replace any existing namespace binding
1362
1363 Example:
1364 ```python
1365 graph.bind("foaf", "http://xmlns.com/foaf/0.1/")
1366 ```
1367 """
1368 # TODO FIXME: This method's behaviour should be simplified and made
1369 # more robust. If the method cannot do what it is asked it should raise
1370 # an exception, it is also unclear why this method has all the
1371 # different modes. It seems to just make it more complex to use, maybe
1372 # it should be clarified when someone will need to use override=False
1373 # and replace=False. And also why silent failure here is preferred over
1374 # raising an exception.
1375 return self.namespace_manager.bind(
1376 prefix, namespace, override=override, replace=replace
1377 )
1378
1379 def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]:
1380 """Generator over all the prefix, namespace tuples
1381
1382 Returns:
1383 Generator yielding prefix, namespace tuples
1384 """
1385 for prefix, namespace in self.namespace_manager.namespaces(): # noqa: F402
1386 yield prefix, namespace
1387
1388 def absolutize(self, uri: str, defrag: int = 1) -> URIRef:
1389 """Turn uri into an absolute URI if it's not one already"""
1390 return self.namespace_manager.absolutize(uri, defrag)
1391
1392 # no destination and non-None positional encoding
1393 @overload
1394 def serialize(
1395 self,
1396 destination: None,
1397 format: str,
1398 base: Optional[str],
1399 encoding: str,
1400 **args: Any,
1401 ) -> bytes: ...
1402
1403 # no destination and non-None keyword encoding
1404 @overload
1405 def serialize(
1406 self,
1407 destination: None = ...,
1408 format: str = ...,
1409 base: Optional[str] = ...,
1410 *,
1411 encoding: str,
1412 **args: Any,
1413 ) -> bytes: ...
1414
1415 # no destination and None encoding
1416 @overload
1417 def serialize(
1418 self,
1419 destination: None = ...,
1420 format: str = ...,
1421 base: Optional[str] = ...,
1422 encoding: None = ...,
1423 **args: Any,
1424 ) -> str: ...
1425
1426 # non-None destination
1427 @overload
1428 def serialize(
1429 self,
1430 destination: Union[str, pathlib.PurePath, IO[bytes]],
1431 format: str = ...,
1432 base: Optional[str] = ...,
1433 encoding: Optional[str] = ...,
1434 **args: Any,
1435 ) -> Graph: ...
1436
1437 # fallback
1438 @overload
1439 def serialize(
1440 self,
1441 destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = ...,
1442 format: str = ...,
1443 base: Optional[str] = ...,
1444 encoding: Optional[str] = ...,
1445 **args: Any,
1446 ) -> Union[bytes, str, Graph]: ...
1447
1448 def serialize(
1449 self: _GraphT,
1450 destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None,
1451 format: str = "turtle",
1452 base: Optional[str] = None,
1453 encoding: Optional[str] = None,
1454 **args: Any,
1455 ) -> Union[bytes, str, _GraphT]:
1456 """Serialize the graph.
1457
1458 Args:
1459 destination: The destination to serialize the graph to. This can be a path as a
1460 string or pathlib.PurePath object, or it can be an IO[bytes] like object.
1461 If this parameter is not supplied the serialized graph will be returned.
1462 format: The format that the output should be written in. This value
1463 references a Serializer plugin.
1464 Format support is managed with [plugins][rdflib.plugin].
1465 Defaults to "turtle" and some other formats are builtin,
1466 like "xml" and "trix".
1467 See also [serialize module][rdflib.plugins.parsers].
1468 base: The base IRI for formats that support it. For the turtle format this
1469 will be used as the @base directive.
1470 encoding: Encoding of output.
1471 args: Additional arguments to pass to the Serializer that will be used.
1472
1473 Returns:
1474 The serialized graph if `destination` is None. The serialized graph is returned
1475 as str if no encoding is specified, and as bytes if an encoding is specified.
1476
1477 self (i.e. the Graph instance) if `destination` is not None.
1478 """
1479
1480 # if base is not given as attribute use the base set for the graph
1481 if base is None:
1482 base = self.base
1483
1484 serializer = plugin.get(format, Serializer)(self)
1485 stream: IO[bytes]
1486 if destination is None:
1487 stream = BytesIO()
1488 if encoding is None:
1489 serializer.serialize(stream, base=base, encoding="utf-8", **args)
1490 return stream.getvalue().decode("utf-8")
1491 else:
1492 serializer.serialize(stream, base=base, encoding=encoding, **args)
1493 return stream.getvalue()
1494 if hasattr(destination, "write"):
1495 stream = cast(IO[bytes], destination)
1496 serializer.serialize(stream, base=base, encoding=encoding, **args)
1497 else:
1498 if isinstance(destination, pathlib.PurePath):
1499 os_path = str(destination)
1500 else:
1501 location = cast(str, destination)
1502 scheme, netloc, path, params, _query, fragment = urlparse(location)
1503 if scheme == "file":
1504 if netloc != "":
1505 raise ValueError(
1506 f"the file URI {location!r} has an authority component which is not supported"
1507 )
1508 os_path = url2pathname(path)
1509 else:
1510 os_path = location
1511 with open(os_path, "wb") as stream:
1512 serializer.serialize(stream, base=base, encoding=encoding, **args)
1513 return self
1514
1515 def print(
1516 self,
1517 format: str = "turtle",
1518 encoding: str = "utf-8",
1519 out: Optional[TextIO] = None,
1520 ) -> None:
1521 print(
1522 self.serialize(None, format=format, encoding=encoding).decode(encoding),
1523 file=out,
1524 flush=True,
1525 )
1526
1527 def parse(
1528 self,
1529 source: Optional[
1530 Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
1531 ] = None,
1532 publicID: Optional[str] = None, # noqa: N803
1533 format: Optional[str] = None,
1534 location: Optional[str] = None,
1535 file: Optional[Union[BinaryIO, TextIO]] = None,
1536 data: Optional[Union[str, bytes]] = None,
1537 **args: Any,
1538 ) -> Graph:
1539 """Parse an RDF source adding the resulting triples to the Graph.
1540
1541 The source is specified using one of source, location, file or data.
1542
1543 Args:
1544 source: An `xml.sax.xmlreader.InputSource`, file-like object,
1545 `pathlib.Path` like object, or string. In the case of a string the string
1546 is the location of the source.
1547 publicID: The logical URI to use as the document base. If None
1548 specified the document location is used (at least in the case where
1549 there is a document location). This is used as the base URI when
1550 resolving relative URIs in the source document, as defined in `IETF
1551 RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-5.1.4>`_,
1552 given the source document does not define a base URI.
1553 format: Used if format can not be determined from source, e.g.
1554 file extension or Media Type. Format support is managed
1555 with [plugins][rdflib.plugin].
1556 Available formats are e.g. "turle", "xml", "n3", "nt" and "trix"
1557 or see [parser module][rdflib.plugins.parsers].
1558 location: A string indicating the relative or absolute URL of the
1559 source. `Graph`'s absolutize method is used if a relative location
1560 is specified.
1561 file: A file-like object.
1562 data: A string containing the data to be parsed.
1563 args: Additional arguments to pass to the parser.
1564
1565 Returns:
1566 self, i.e. the Graph instance.
1567
1568 Example:
1569 ```python
1570 >>> my_data = '''
1571 ... <rdf:RDF
1572 ... xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
1573 ... xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
1574 ... >
1575 ... <rdf:Description>
1576 ... <rdfs:label>Example</rdfs:label>
1577 ... <rdfs:comment>This is really just an example.</rdfs:comment>
1578 ... </rdf:Description>
1579 ... </rdf:RDF>
1580 ... '''
1581 >>> import os, tempfile
1582 >>> fd, file_name = tempfile.mkstemp()
1583 >>> f = os.fdopen(fd, "w")
1584 >>> dummy = f.write(my_data) # Returns num bytes written
1585 >>> f.close()
1586
1587 >>> g = Graph()
1588 >>> result = g.parse(data=my_data, format="application/rdf+xml")
1589 >>> len(g)
1590 2
1591
1592 >>> g = Graph()
1593 >>> result = g.parse(location=file_name, format="application/rdf+xml")
1594 >>> len(g)
1595 2
1596
1597 >>> g = Graph()
1598 >>> with open(file_name, "r") as f:
1599 ... result = g.parse(f, format="application/rdf+xml")
1600 >>> len(g)
1601 2
1602
1603 >>> os.remove(file_name)
1604
1605 >>> # default turtle parsing
1606 >>> result = g.parse(data="<http://example.com/a> <http://example.com/a> <http://example.com/a> .")
1607 >>> len(g)
1608 3
1609
1610 ```
1611
1612 !!! warning "Caution"
1613 This method can access directly or indirectly requested network or
1614 file resources, for example, when parsing JSON-LD documents with
1615 `@context` directives that point to a network location.
1616
1617 When processing untrusted or potentially malicious documents,
1618 measures should be taken to restrict network and file access.
1619
1620 For information on available security measures, see the RDFLib
1621 [Security Considerations](../security_considerations.md)
1622 documentation.
1623 """
1624
1625 source = create_input_source(
1626 source=source,
1627 publicID=publicID,
1628 location=location,
1629 file=file,
1630 data=data,
1631 format=format,
1632 )
1633 if format is None:
1634 format = source.content_type
1635 could_not_guess_format = False
1636 if format is None:
1637 if (
1638 hasattr(source, "file")
1639 and getattr(source.file, "name", None)
1640 and isinstance(source.file.name, str)
1641 ):
1642 format = rdflib.util.guess_format(source.file.name)
1643 if format is None:
1644 format = "turtle"
1645 could_not_guess_format = True
1646 try:
1647 parser = plugin.get(format, Parser)()
1648 except plugin.PluginException:
1649 # Handle the case when a URLInputSource returns RDF but with the headers
1650 # as a format that does not exist in the plugin system.
1651 # Use guess_format to guess the format based on the input's file suffix.
1652 format = rdflib.util.guess_format(
1653 source if not isinstance(source, InputSource) else str(source)
1654 )
1655 if format is None:
1656 raise
1657 parser = plugin.get(format, Parser)()
1658 try:
1659 # TODO FIXME: Parser.parse should have **kwargs argument.
1660 parser.parse(source, self, **args)
1661 except SyntaxError as se:
1662 if could_not_guess_format:
1663 raise ParserError(
1664 "Could not guess RDF format for %r from file extension so tried Turtle but failed."
1665 "You can explicitly specify format using the format argument."
1666 % source
1667 )
1668 else:
1669 raise se
1670 finally:
1671 if source.auto_close:
1672 source.close()
1673 return self
1674
1675 def query(
1676 self,
1677 query_object: Union[str, Query],
1678 processor: Union[str, query.Processor] = "sparql",
1679 result: Union[str, Type[query.Result]] = "sparql",
1680 initNs: Optional[Mapping[str, Any]] = None, # noqa: N803
1681 initBindings: Optional[Mapping[str, Identifier]] = None, # noqa: N803
1682 use_store_provided: bool = True,
1683 **kwargs: Any,
1684 ) -> query.Result:
1685 """
1686 Query this graph.
1687
1688 Args:
1689 query_object: The query string or object to execute.
1690 processor: The query processor to use. Default is "sparql".
1691 result: The result format to use. Default is "sparql".
1692 initNs: Initial namespaces to use for resolving prefixes in the query.
1693 If none are given, the namespaces from the graph's namespace manager are used.
1694 initBindings: Initial variable bindings to use. A type of 'prepared queries'
1695 can be realized by providing these bindings.
1696 use_store_provided: Whether to use the store's query method if available.
1697 kwargs: Additional arguments to pass to the query processor.
1698
1699 Returns:
1700 A [`rdflib.query.Result`][`rdflib.query.Result`] instance.
1701
1702 !!! warning "Caution"
1703 This method can access indirectly requested network endpoints, for
1704 example, query processing will attempt to access network endpoints
1705 specified in `SERVICE` directives.
1706
1707 When processing untrusted or potentially malicious queries, measures
1708 should be taken to restrict network and file access.
1709
1710 For information on available security measures, see the RDFLib
1711 [Security Considerations](../security_considerations.md)
1712 documentation.
1713 """
1714
1715 initBindings = initBindings or {} # noqa: N806
1716 initNs = initNs or dict(self.namespaces()) # noqa: N806
1717
1718 if self.default_union:
1719 query_graph = "__UNION__"
1720 elif isinstance(self, ConjunctiveGraph):
1721 query_graph = self.default_context.identifier
1722 else:
1723 query_graph = self.identifier
1724 if hasattr(self.store, "query") and use_store_provided:
1725 try:
1726 return self.store.query(
1727 query_object,
1728 initNs,
1729 initBindings,
1730 query_graph,
1731 **kwargs,
1732 )
1733 except NotImplementedError:
1734 pass # store has no own implementation
1735
1736 if not isinstance(result, query.Result):
1737 result = plugin.get(cast(str, result), query.Result)
1738 if not isinstance(processor, query.Processor):
1739 processor = plugin.get(processor, query.Processor)(self)
1740
1741 # type error: Argument 1 to "Result" has incompatible type "Mapping[str, Any]"; expected "str"
1742 return result(processor.query(query_object, initBindings, initNs, **kwargs)) # type: ignore[arg-type]
1743
1744 def update(
1745 self,
1746 update_object: Union[Update, str],
1747 processor: Union[str, rdflib.query.UpdateProcessor] = "sparql",
1748 initNs: Optional[Mapping[str, Any]] = None, # noqa: N803
1749 initBindings: Optional[Mapping[str, Identifier]] = None, # noqa: N803
1750 use_store_provided: bool = True,
1751 **kwargs: Any,
1752 ) -> None:
1753 """Update this graph with the given update query.
1754
1755 Args:
1756 update_object: The update query string or object to execute.
1757 processor: The update processor to use. Default is "sparql".
1758 initNs: Initial namespaces to use for resolving prefixes in the query.
1759 If none are given, the namespaces from the graph's namespace manager are used.
1760 initBindings: Initial variable bindings to use.
1761 use_store_provided: Whether to use the store's update method if available.
1762 kwargs: Additional arguments to pass to the update processor.
1763
1764 !!! warning "Caution"
1765 This method can access indirectly requested network endpoints, for
1766 example, query processing will attempt to access network endpoints
1767 specified in `SERVICE` directives.
1768
1769 When processing untrusted or potentially malicious queries, measures
1770 should be taken to restrict network and file access.
1771
1772 For information on available security measures, see the RDFLib
1773 Security Considerations documentation.
1774 """
1775 initBindings = initBindings or {} # noqa: N806
1776 initNs = initNs or dict(self.namespaces()) # noqa: N806
1777
1778 if self.default_union:
1779 query_graph = "__UNION__"
1780 elif isinstance(self, ConjunctiveGraph):
1781 query_graph = self.default_context.identifier
1782 else:
1783 query_graph = self.identifier
1784
1785 if hasattr(self.store, "update") and use_store_provided:
1786 try:
1787 return self.store.update(
1788 update_object,
1789 initNs,
1790 initBindings,
1791 query_graph,
1792 **kwargs,
1793 )
1794 except NotImplementedError:
1795 pass # store has no own implementation
1796
1797 if not isinstance(processor, query.UpdateProcessor):
1798 processor = plugin.get(processor, query.UpdateProcessor)(self)
1799
1800 return processor.update(update_object, initBindings, initNs, **kwargs)
1801
1802 def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str:
1803 """Return an n3 identifier for the Graph"""
1804 return "[%s]" % self.identifier.n3(namespace_manager=namespace_manager)
1805
1806 def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
1807 return (
1808 Graph,
1809 (
1810 self.store,
1811 self.identifier,
1812 ),
1813 )
1814
1815 def isomorphic(self, other: Graph) -> bool:
1816 """Check if this graph is isomorphic to another graph.
1817
1818 Performs a basic check if these graphs are the same.
1819 If no BNodes are involved, this is accurate.
1820
1821 Args:
1822 other: The graph to compare with.
1823
1824 Returns:
1825 True if the graphs are isomorphic, False otherwise.
1826
1827 Note:
1828 This is only an approximation. See rdflib.compare for a correct
1829 implementation of isomorphism checks.
1830 """
1831 # TODO: this is only an approximation.
1832 if len(self) != len(other):
1833 return False
1834 for s, p, o in self:
1835 if not isinstance(s, BNode) and not isinstance(o, BNode):
1836 if not (s, p, o) in other: # noqa: E713
1837 return False
1838 for s, p, o in other:
1839 if not isinstance(s, BNode) and not isinstance(o, BNode):
1840 if not (s, p, o) in self: # noqa: E713
1841 return False
1842 # TODO: very well could be a false positive at this point yet.
1843 return True
1844
1845 def connected(self) -> bool:
1846 """Check if the Graph is connected.
1847
1848 The Graph is considered undirectional.
1849
1850 Returns:
1851 True if all nodes have been visited and there are no unvisited nodes left,
1852 False otherwise.
1853
1854 Note:
1855 Performs a search on the Graph, starting from a random node. Then
1856 iteratively goes depth-first through the triplets where the node is
1857 subject and object.
1858 """
1859 all_nodes = list(self.all_nodes())
1860 discovered = []
1861
1862 # take a random one, could also always take the first one, doesn't
1863 # really matter.
1864 if not all_nodes:
1865 return False
1866
1867 visiting = [all_nodes[random.randrange(len(all_nodes))]]
1868 while visiting:
1869 x = visiting.pop()
1870 if x not in discovered:
1871 discovered.append(x)
1872 for new_x in self.objects(subject=x):
1873 if new_x not in discovered and new_x not in visiting:
1874 visiting.append(new_x)
1875 for new_x in self.subjects(object=x):
1876 if new_x not in discovered and new_x not in visiting:
1877 visiting.append(new_x)
1878
1879 # optimisation by only considering length, since no new objects can
1880 # be introduced anywhere.
1881 if len(all_nodes) == len(discovered):
1882 return True
1883 else:
1884 return False
1885
1886 def all_nodes(self) -> Set[Node]:
1887 res = set(self.objects())
1888 res.update(self.subjects())
1889 return res
1890
1891 def collection(self, identifier: _SubjectType) -> Collection:
1892 """Create a new `Collection` instance.
1893
1894 Args:
1895 identifier: A URIRef or BNode instance.
1896
1897 Returns:
1898 A new Collection instance.
1899
1900 Example:
1901 ```python
1902 >>> graph = Graph()
1903 >>> uri = URIRef("http://example.org/resource")
1904 >>> collection = graph.collection(uri)
1905 >>> assert isinstance(collection, Collection)
1906 >>> assert collection.uri is uri
1907 >>> assert collection.graph is graph
1908 >>> collection += [ Literal(1), Literal(2) ]
1909
1910 ```
1911 """
1912
1913 return Collection(self, identifier)
1914
1915 def resource(self, identifier: Union[Node, str]) -> Resource:
1916 """Create a new ``Resource`` instance.
1917
1918 Args:
1919 identifier: A URIRef or BNode instance.
1920
1921 Returns:
1922 A new Resource instance.
1923
1924 Example:
1925 ```python
1926 >>> graph = Graph()
1927 >>> uri = URIRef("http://example.org/resource")
1928 >>> resource = graph.resource(uri)
1929 >>> assert isinstance(resource, Resource)
1930 >>> assert resource.identifier is uri
1931 >>> assert resource.graph is graph
1932
1933 ```
1934 """
1935 if not isinstance(identifier, Node):
1936 identifier = URIRef(identifier)
1937 return Resource(self, identifier)
1938
1939 def _process_skolem_tuples(
1940 self, target: Graph, func: Callable[[_TripleType], _TripleType]
1941 ) -> None:
1942 for t in self.triples((None, None, None)):
1943 target.add(func(t))
1944
1945 def skolemize(
1946 self,
1947 new_graph: Optional[Graph] = None,
1948 bnode: Optional[BNode] = None,
1949 authority: Optional[str] = None,
1950 basepath: Optional[str] = None,
1951 ) -> Graph:
1952 def do_skolemize(bnode: BNode, t: _TripleType) -> _TripleType:
1953 (s, p, o) = t
1954 if s == bnode:
1955 if TYPE_CHECKING:
1956 assert isinstance(s, BNode)
1957 s = s.skolemize(authority=authority, basepath=basepath)
1958 if o == bnode:
1959 if TYPE_CHECKING:
1960 assert isinstance(o, BNode)
1961 o = o.skolemize(authority=authority, basepath=basepath)
1962 return s, p, o
1963
1964 def do_skolemize2(t: _TripleType) -> _TripleType:
1965 (s, p, o) = t
1966 if isinstance(s, BNode):
1967 s = s.skolemize(authority=authority, basepath=basepath)
1968 if isinstance(o, BNode):
1969 o = o.skolemize(authority=authority, basepath=basepath)
1970 return s, p, o
1971
1972 retval = Graph() if new_graph is None else new_graph
1973
1974 if bnode is None:
1975 self._process_skolem_tuples(retval, do_skolemize2)
1976 elif isinstance(bnode, BNode):
1977 # type error: Argument 1 to "do_skolemize" has incompatible type "Optional[BNode]"; expected "BNode"
1978 self._process_skolem_tuples(retval, lambda t: do_skolemize(bnode, t)) # type: ignore[arg-type, unused-ignore]
1979
1980 return retval
1981
1982 def de_skolemize(
1983 self, new_graph: Optional[Graph] = None, uriref: Optional[URIRef] = None
1984 ) -> Graph:
1985 def do_de_skolemize(uriref: URIRef, t: _TripleType) -> _TripleType:
1986 (s, p, o) = t
1987 if s == uriref:
1988 if TYPE_CHECKING:
1989 assert isinstance(s, URIRef)
1990 s = s.de_skolemize()
1991 if o == uriref:
1992 if TYPE_CHECKING:
1993 assert isinstance(o, URIRef)
1994 o = o.de_skolemize()
1995 return s, p, o
1996
1997 def do_de_skolemize2(t: _TripleType) -> _TripleType:
1998 (s, p, o) = t
1999
2000 if RDFLibGenid._is_rdflib_skolem(s):
2001 # type error: Argument 1 to "RDFLibGenid" has incompatible type "Node"; expected "str"
2002 s = RDFLibGenid(s).de_skolemize() # type: ignore[arg-type]
2003 elif Genid._is_external_skolem(s):
2004 # type error: Argument 1 to "Genid" has incompatible type "Node"; expected "str"
2005 s = Genid(s).de_skolemize() # type: ignore[arg-type]
2006
2007 if isinstance(o, URIRef):
2008 if RDFLibGenid._is_rdflib_skolem(o):
2009 o = RDFLibGenid(o).de_skolemize()
2010 elif Genid._is_external_skolem(o):
2011 o = Genid(o).de_skolemize()
2012
2013 return s, p, o
2014
2015 retval = Graph() if new_graph is None else new_graph
2016
2017 if uriref is None:
2018 self._process_skolem_tuples(retval, do_de_skolemize2)
2019 elif isinstance(uriref, Genid):
2020 # type error: Argument 1 to "do_de_skolemize" has incompatible type "Optional[URIRef]"; expected "URIRef"
2021 self._process_skolem_tuples(retval, lambda t: do_de_skolemize(uriref, t)) # type: ignore[arg-type, unused-ignore]
2022
2023 return retval
2024
2025 def cbd(
2026 self,
2027 resource: _SubjectType,
2028 *,
2029 target_graph: Graph | None = None,
2030 include_reifications: bool = True,
2031 ) -> Graph:
2032 """Retrieves the Concise Bounded Description of a Resource from a Graph.
2033
2034 Args:
2035 resource: A URIRef object, the Resource to query for.
2036 target_graph: Optionally, a graph to add the CBD to; otherwise,
2037 a new graph is created for the CBD.
2038 include_reifications: If False, skip Rule 3 to exclude reified statements (default: True)
2039
2040 Returns:
2041 A Graph, subgraph of self if no graph was provided otherwise the provided graph.
2042
2043 Note:
2044 Concise Bounded Description (CBD) is defined as:
2045
2046 Given a particular node (the starting node) in a particular RDF graph (the source graph),
2047 a subgraph of that particular graph, taken to comprise a concise bounded description of
2048 the resource denoted by the starting node, can be identified as follows:
2049
2050 1. Include in the subgraph all statements in the source graph where the subject of the
2051 statement is the starting node;
2052
2053 2. Recursively, for all statements identified in the subgraph thus far having a blank
2054 node object, include in the subgraph all statements in the source graph where the
2055 subject of the statement is the blank node in question and which are not already
2056 included in the subgraph.
2057
2058 3. Recursively, for all statements included in the subgraph thus far, for all
2059 reifications of each statement in the source graph, include the concise bounded
2060 description beginning from the rdf:Statement node of each reification.
2061
2062 This results in a subgraph where the object nodes are either URI references, literals,
2063 or blank nodes not serving as the subject of any statement in the graph.
2064
2065 If include_reifications is set to False, Rule 3 above will be skipped, meaning reified statements
2066 will not be included in the CBD. This can improve performance when reified statements are not present
2067 or can be used to deliberately exclude them from the result.
2068 """
2069 # If no target graph is provided, create a new Graph to hold the CBD.
2070 if target_graph is None:
2071 subgraph = Graph()
2072 else:
2073 subgraph = target_graph
2074
2075 def add_to_cbd(uri: _SubjectType) -> None:
2076 # Rule 3 Preparation:
2077 # If reifications are to be included, build an index mapping triples with
2078 # this subject to the set of reification nodes (rdf:Statement nodes) that reify them.
2079 if include_reifications:
2080 reif_index: dict[_TripleType, set[_SubjectType]] = {}
2081 for stmt in self.subjects(RDF.subject, uri):
2082 p: _PredicateType = self.value(stmt, RDF.predicate) # type: ignore[assignment]
2083 o = self.value(stmt, RDF.object)
2084 if p is not None and o is not None:
2085 triple = (uri, p, o)
2086 if triple not in reif_index:
2087 reif_index[triple] = {stmt}
2088 else:
2089 reif_index[triple].add(stmt)
2090
2091 # For all triples where the subject is the current subject (Rule 1)
2092 for s, p, o in self.triples((uri, None, None)):
2093 # Add the triple to the CBD subgraph
2094 subgraph.add((s, p, o))
2095 # If the object is a blank node, recursively add its CBD (Rule 2)
2096 if type(o) is BNode and (o, None, None) not in subgraph:
2097 add_to_cbd(o)
2098
2099 # If including reifications (Rule 3):
2100 if include_reifications:
2101 # For each reification node of this triple, recursively add its CBD
2102 stmts = reif_index.get((s, p, o), set())
2103 for stmt in stmts:
2104 if (stmt, None, None) not in subgraph:
2105 add_to_cbd(stmt)
2106
2107 # Start the CBD construction from the given resource
2108 add_to_cbd(resource)
2109
2110 return subgraph
2111
2112
2113_ContextType = Graph
2114
2115
2116class ConjunctiveGraph(Graph):
2117 """A ConjunctiveGraph is an (unnamed) aggregation of all the named
2118 graphs in a store.
2119
2120 !!! warning "Deprecation notice"
2121 ConjunctiveGraph is deprecated, use [`rdflib.graph.Dataset`][rdflib.graph.Dataset] instead.
2122
2123 It has a `default` graph, whose name is associated with the
2124 graph throughout its life. Constructor can take an identifier
2125 to use as the name of this default graph or it will assign a
2126 BNode.
2127
2128 All methods that add triples work against this default graph.
2129
2130 All queries are carried out against the union of all graphs.
2131 """
2132
2133 _default_context: _ContextType
2134
2135 def __init__(
2136 self,
2137 store: Union[Store, str] = "default",
2138 identifier: Optional[Union[IdentifiedNode, str]] = None,
2139 default_graph_base: Optional[str] = None,
2140 ):
2141 super(ConjunctiveGraph, self).__init__(store, identifier=identifier)
2142
2143 if type(self) is ConjunctiveGraph:
2144 warnings.warn(
2145 "ConjunctiveGraph is deprecated, use Dataset instead.",
2146 DeprecationWarning,
2147 stacklevel=2,
2148 )
2149
2150 assert self.store.context_aware, (
2151 "ConjunctiveGraph must be backed by" " a context aware store."
2152 )
2153 self.context_aware = True
2154 self.default_union = True # Conjunctive!
2155 self._default_context: _ContextType = Graph(
2156 store=self.store, identifier=identifier or BNode(), base=default_graph_base
2157 )
2158
2159 @property
2160 def default_context(self):
2161 return self._default_context
2162
2163 @default_context.setter
2164 def default_context(self, value):
2165 self._default_context = value
2166
2167 def __str__(self) -> str:
2168 pattern = (
2169 "[a rdflib:ConjunctiveGraph;rdflib:storage "
2170 "[a rdflib:Store;rdfs:label '%s']]"
2171 )
2172 return pattern % self.store.__class__.__name__
2173
2174 @overload
2175 def _spoc(
2176 self,
2177 triple_or_quad: _QuadType,
2178 default: bool = False,
2179 ) -> _QuadType: ...
2180
2181 @overload
2182 def _spoc(
2183 self,
2184 triple_or_quad: Union[_TripleType, _OptionalQuadType],
2185 default: bool = False,
2186 ) -> _OptionalQuadType: ...
2187
2188 @overload
2189 def _spoc(
2190 self,
2191 triple_or_quad: None,
2192 default: bool = False,
2193 ) -> Tuple[None, None, None, Optional[Graph]]: ...
2194
2195 @overload
2196 def _spoc(
2197 self,
2198 triple_or_quad: Optional[_TripleOrQuadPatternType],
2199 default: bool = False,
2200 ) -> _QuadPatternType: ...
2201
2202 @overload
2203 def _spoc(
2204 self,
2205 triple_or_quad: _TripleOrQuadSelectorType,
2206 default: bool = False,
2207 ) -> _QuadSelectorType: ...
2208
2209 @overload
2210 def _spoc(
2211 self,
2212 triple_or_quad: Optional[_TripleOrQuadSelectorType],
2213 default: bool = False,
2214 ) -> _QuadSelectorType: ...
2215
2216 def _spoc(
2217 self,
2218 triple_or_quad: Optional[_TripleOrQuadSelectorType],
2219 default: bool = False,
2220 ) -> _QuadSelectorType:
2221 """
2222 helper method for having methods that support
2223 either triples or quads
2224 """
2225 if triple_or_quad is None:
2226 return (None, None, None, self.default_context if default else None)
2227 if len(triple_or_quad) == 3:
2228 c = self.default_context if default else None
2229 # type error: Too many values to unpack (3 expected, 4 provided)
2230 (s, p, o) = triple_or_quad # type: ignore[misc, unused-ignore]
2231 elif len(triple_or_quad) == 4:
2232 # type error: Need more than 3 values to unpack (4 expected)
2233 (s, p, o, c) = triple_or_quad # type: ignore[misc, unused-ignore]
2234 c = self._graph(c)
2235 return s, p, o, c
2236
2237 def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool:
2238 """Support for 'triple/quad in graph' syntax"""
2239 s, p, o, c = self._spoc(triple_or_quad)
2240 for t in self.triples((s, p, o), context=c):
2241 return True
2242 return False
2243
2244 def add(
2245 self: _ConjunctiveGraphT,
2246 triple_or_quad: _TripleOrOptionalQuadType,
2247 ) -> _ConjunctiveGraphT:
2248 """Add a triple or quad to the store.
2249
2250 if a triple is given it is added to the default context
2251 """
2252
2253 s, p, o, c = self._spoc(triple_or_quad, default=True)
2254
2255 _assertnode(s, p, o)
2256
2257 # type error: Argument "context" to "add" of "Store" has incompatible type "Optional[Graph]"; expected "Graph"
2258 self.store.add((s, p, o), context=c, quoted=False) # type: ignore[arg-type]
2259 return self
2260
2261 @overload
2262 def _graph(self, c: Union[Graph, _ContextIdentifierType, str]) -> Graph: ...
2263
2264 @overload
2265 def _graph(self, c: None) -> None: ...
2266
2267 def _graph(
2268 self,
2269 c: Optional[Union[Graph, _ContextIdentifierType, str]],
2270 ) -> Optional[Graph]:
2271 if c is None:
2272 return None
2273 if isinstance(c, (Dataset, ConjunctiveGraph)):
2274 # Preserve the old behaviour for datasets.
2275 return c
2276 if isinstance(c, Graph):
2277 # Resolve to a graph backed by this dataset store.
2278 return self.get_context(c.identifier)
2279 return self.get_context(c)
2280
2281 def addN( # noqa: N802
2282 self: _ConjunctiveGraphT, quads: Iterable[_QuadType]
2283 ) -> _ConjunctiveGraphT:
2284 """Add a sequence of triples with context"""
2285
2286 self.store.addN(
2287 (s, p, o, self._graph(c)) for s, p, o, c in quads if _assertnode(s, p, o)
2288 )
2289 return self
2290
2291 # type error: Argument 1 of "remove" is incompatible with supertype "Graph"; supertype defines the argument type as "Tuple[Optional[Node], Optional[Node], Optional[Node]]"
2292 def remove(self: _ConjunctiveGraphT, triple_or_quad: _TripleOrOptionalQuadType) -> _ConjunctiveGraphT: # type: ignore[override]
2293 """Removes a triple or quads
2294
2295 if a triple is given it is removed from all contexts
2296 a quad is removed from the given context only
2297 """
2298 s, p, o, c = self._spoc(triple_or_quad)
2299
2300 self.store.remove((s, p, o), context=c)
2301 return self
2302
2303 @overload
2304 def triples(
2305 self,
2306 triple_or_quad: _TripleOrQuadPatternType,
2307 context: Optional[_ContextType] = ...,
2308 ) -> Generator[_TripleType, None, None]: ...
2309
2310 @overload
2311 def triples(
2312 self,
2313 triple_or_quad: _TripleOrQuadPathPatternType,
2314 context: Optional[_ContextType] = ...,
2315 ) -> Generator[_TriplePathType, None, None]: ...
2316
2317 @overload
2318 def triples(
2319 self,
2320 triple_or_quad: _TripleOrQuadSelectorType,
2321 context: Optional[_ContextType] = ...,
2322 ) -> Generator[_TripleOrTriplePathType, None, None]: ...
2323
2324 def triples(
2325 self,
2326 triple_or_quad: _TripleOrQuadSelectorType,
2327 context: Optional[_ContextType] = None,
2328 ) -> Generator[_TripleOrTriplePathType, None, None]:
2329 """Iterate over all the triples in the entire conjunctive graph
2330
2331 For legacy reasons, this can take the context to query either
2332 as a fourth element of the quad, or as the explicit context
2333 keyword parameter. The kw param takes precedence.
2334 """
2335
2336 s, p, o, c = self._spoc(triple_or_quad)
2337 context = self._graph(context or c)
2338
2339 if self.default_union:
2340 if context == self.default_context:
2341 context = None
2342 else:
2343 if context is None:
2344 context = self.default_context
2345
2346 if isinstance(p, Path):
2347 if context is None:
2348 context = self
2349
2350 for s, o in p.eval(context, s, o):
2351 yield s, p, o
2352 else:
2353 for (s, p, o), cg in self.store.triples((s, p, o), context=context):
2354 yield s, p, o
2355
2356 def quads(
2357 self, triple_or_quad: Optional[_TripleOrQuadPatternType] = None
2358 ) -> Generator[_OptionalQuadType, None, None]:
2359 """Iterate over all the quads in the entire conjunctive graph"""
2360
2361 s, p, o, c = self._spoc(triple_or_quad)
2362
2363 for (s, p, o), cg in self.store.triples((s, p, o), context=c):
2364 for ctx in cg:
2365 yield s, p, o, ctx
2366
2367 def triples_choices(
2368 self,
2369 triple: _TripleChoiceType,
2370 context: Optional[_ContextType] = None,
2371 ) -> Generator[_TripleType, None, None]:
2372 """Iterate over all the triples in the entire conjunctive graph"""
2373 s, p, o = triple
2374 if context is None:
2375 if not self.default_union:
2376 context = self.default_context
2377 else:
2378 context = self._graph(context)
2379 # 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]]]"
2380 # type error note: unpacking discards type info
2381 for (s1, p1, o1), cg in self.store.triples_choices((s, p, o), context=context): # type: ignore[arg-type]
2382 yield s1, p1, o1
2383
2384 def __len__(self) -> int:
2385 """Number of triples in the entire conjunctive graph"""
2386 return self.store.__len__()
2387
2388 def contexts(
2389 self, triple: Optional[_TripleType] = None
2390 ) -> Generator[_ContextType, None, None]:
2391 """Iterate over all contexts in the graph
2392
2393 If triple is specified, iterate over all contexts the triple is in.
2394 """
2395 for context in self.store.contexts(triple):
2396 if isinstance(context, Graph):
2397 # TODO: One of these should never happen and probably
2398 # should raise an exception rather than smoothing over
2399 # the weirdness - see #225
2400 yield context
2401 else:
2402 # type error: Statement is unreachable
2403 yield self.get_context(context) # type: ignore[unreachable]
2404
2405 def get_graph(self, identifier: _ContextIdentifierType) -> Union[Graph, None]:
2406 """Returns the graph identified by given identifier"""
2407 return [x for x in self.contexts() if x.identifier == identifier][0]
2408
2409 def get_context(
2410 self,
2411 identifier: Optional[Union[_ContextIdentifierType, str]],
2412 quoted: bool = False,
2413 base: Optional[str] = None,
2414 ) -> Graph:
2415 """Return a context graph for the given identifier
2416
2417 identifier must be a URIRef or BNode.
2418 """
2419 return Graph(
2420 store=self.store,
2421 identifier=identifier,
2422 namespace_manager=self.namespace_manager,
2423 base=base,
2424 )
2425
2426 def remove_context(self, context: _ContextType) -> None:
2427 """Removes the given context from the graph"""
2428 self.store.remove((None, None, None), context)
2429
2430 def context_id(self, uri: str, context_id: Optional[str] = None) -> URIRef:
2431 """URI#context"""
2432 uri = uri.split("#", 1)[0]
2433 if context_id is None:
2434 context_id = "#context"
2435 return URIRef(context_id, base=uri)
2436
2437 def parse(
2438 self,
2439 source: Optional[
2440 Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
2441 ] = None,
2442 publicID: Optional[str] = None, # noqa: N803
2443 format: Optional[str] = None,
2444 location: Optional[str] = None,
2445 file: Optional[Union[BinaryIO, TextIO]] = None,
2446 data: Optional[Union[str, bytes]] = None,
2447 **args: Any,
2448 ) -> Graph:
2449 """Parse source adding the resulting triples to its own context (sub graph
2450 of this graph).
2451
2452 See [`rdflib.graph.Graph.parse`][rdflib.graph.Graph.parse] for documentation on arguments.
2453
2454 Args:
2455 source: The source to parse
2456 publicID: The public ID of the source
2457 format: The format of the source
2458 location: The location of the source
2459 file: The file object to parse
2460 data: The data to parse
2461 **args: Additional arguments
2462
2463 Returns:
2464 The graph into which the source was parsed. In the case of n3 it returns
2465 the root context.
2466
2467 Note:
2468 If the source is in a format that does not support named graphs its triples
2469 will be added to the default graph (i.e. ConjunctiveGraph.default_context).
2470
2471 !!! warning "Caution"
2472 This method can access directly or indirectly requested network or
2473 file resources, for example, when parsing JSON-LD documents with
2474 `@context` directives that point to a network location.
2475
2476 When processing untrusted or potentially malicious documents,
2477 measures should be taken to restrict network and file access.
2478
2479 For information on available security measures, see the RDFLib
2480 Security Considerations documentation.
2481
2482 !!! example "Changed in 7.0"
2483 The `publicID` argument is no longer used as the identifier (i.e. name)
2484 of the default graph as was the case before version 7.0. In the case of
2485 sources that do not support named graphs, the `publicID` parameter will
2486 also not be used as the name for the graph that the data is loaded into,
2487 and instead the triples from sources that do not support named graphs will
2488 be loaded into the default graph (i.e. ConjunctiveGraph.default_context).
2489 """
2490
2491 source = create_input_source(
2492 source=source,
2493 publicID=publicID,
2494 location=location,
2495 file=file,
2496 data=data,
2497 format=format,
2498 )
2499
2500 # NOTE on type hint: `xml.sax.xmlreader.InputSource.getPublicId` has no
2501 # type annotations but given that systemId should be a string, and
2502 # given that there is no specific mention of type for publicId, it
2503 # seems reasonable to assume it should also be a string. Furthermore,
2504 # create_input_source will ensure that publicId is not None, though it
2505 # would be good if this guarantee was made more explicit i.e. by type
2506 # hint on InputSource (TODO/FIXME).
2507
2508 context = self.default_context
2509 context.parse(source, publicID=publicID, format=format, **args)
2510 return self
2511
2512 def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
2513 return ConjunctiveGraph, (self.store, self.identifier)
2514
2515
2516DATASET_DEFAULT_GRAPH_ID = URIRef("urn:x-rdflib:default")
2517
2518
2519class Dataset(ConjunctiveGraph):
2520 """
2521 An RDFLib Dataset is an object that stores multiple Named Graphs - instances of
2522 RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single
2523 Graph use.
2524
2525 RDFLib's Dataset class is based on the [RDF 1.2. 'Dataset' definition](https://www.w3.org/TR/rdf12-datasets/):
2526
2527 An RDF dataset is a collection of RDF graphs, and comprises:
2528
2529 - Exactly one default graph, being an RDF graph. The default graph does not
2530 have a name and MAY be empty.
2531 - Zero or more named graphs. Each named graph is a pair consisting of an IRI or
2532 a blank node (the graph name), and an RDF graph. Graph names are unique
2533 within an RDF dataset.
2534
2535 Accordingly, a Dataset allows for `Graph` objects to be added to it with
2536 [`URIRef`][rdflib.term.URIRef] or [`BNode`][rdflib.term.BNode] identifiers and always
2537 creats a default graph with the [`URIRef`][rdflib.term.URIRef] identifier
2538 `urn:x-rdflib:default`.
2539
2540 Dataset extends Graph's Subject, Predicate, Object (s, p, o) 'triple'
2541 structure to include a graph identifier - archaically called Context - producing
2542 'quads' of s, p, o, g.
2543
2544 Triples, or quads, can be added to a Dataset. Triples, or quads with the graph
2545 identifer :code:`urn:x-rdflib:default` go into the default graph.
2546
2547 !!! warning "Deprecation notice"
2548 Dataset builds on the `ConjunctiveGraph` class but that class's direct
2549 use is now deprecated (since RDFLib 7.x) and it should not be used.
2550 `ConjunctiveGraph` will be removed from future RDFLib versions.
2551
2552 Examples of usage and see also the `examples/datast.py` file:
2553
2554 ```python
2555 >>> # Create a new Dataset
2556 >>> ds = Dataset()
2557 >>> # simple triples goes to default graph
2558 >>> ds.add((
2559 ... URIRef("http://example.org/a"),
2560 ... URIRef("http://www.example.org/b"),
2561 ... Literal("foo")
2562 ... )) # doctest: +ELLIPSIS
2563 <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
2564
2565 >>> # Create a graph in the dataset, if the graph name has already been
2566 >>> # used, the corresponding graph will be returned
2567 >>> # (ie, the Dataset keeps track of the constituent graphs)
2568 >>> g = ds.graph(URIRef("http://www.example.com/gr"))
2569
2570 >>> # add triples to the new graph as usual
2571 >>> g.add((
2572 ... URIRef("http://example.org/x"),
2573 ... URIRef("http://example.org/y"),
2574 ... Literal("bar")
2575 ... )) # doctest: +ELLIPSIS
2576 <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
2577 >>> # alternatively: add a quad to the dataset -> goes to the graph
2578 >>> ds.add((
2579 ... URIRef("http://example.org/x"),
2580 ... URIRef("http://example.org/z"),
2581 ... Literal("foo-bar"),
2582 ... g
2583 ... )) # doctest: +ELLIPSIS
2584 <Graph identifier=... (<class 'rdflib.graph.Dataset'>)>
2585
2586 >>> # querying triples return them all regardless of the graph
2587 >>> for t in ds.triples((None,None,None)): # doctest: +SKIP
2588 ... print(t) # doctest: +NORMALIZE_WHITESPACE
2589 (rdflib.term.URIRef("http://example.org/a"),
2590 rdflib.term.URIRef("http://www.example.org/b"),
2591 rdflib.term.Literal("foo"))
2592 (rdflib.term.URIRef("http://example.org/x"),
2593 rdflib.term.URIRef("http://example.org/z"),
2594 rdflib.term.Literal("foo-bar"))
2595 (rdflib.term.URIRef("http://example.org/x"),
2596 rdflib.term.URIRef("http://example.org/y"),
2597 rdflib.term.Literal("bar"))
2598
2599 >>> # querying quads() return quads; the fourth argument can be unrestricted
2600 >>> # (None) or restricted to a graph
2601 >>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP
2602 ... print(q) # doctest: +NORMALIZE_WHITESPACE
2603 (rdflib.term.URIRef("http://example.org/a"),
2604 rdflib.term.URIRef("http://www.example.org/b"),
2605 rdflib.term.Literal("foo"),
2606 None)
2607 (rdflib.term.URIRef("http://example.org/x"),
2608 rdflib.term.URIRef("http://example.org/y"),
2609 rdflib.term.Literal("bar"),
2610 rdflib.term.URIRef("http://www.example.com/gr"))
2611 (rdflib.term.URIRef("http://example.org/x"),
2612 rdflib.term.URIRef("http://example.org/z"),
2613 rdflib.term.Literal("foo-bar"),
2614 rdflib.term.URIRef("http://www.example.com/gr"))
2615
2616 >>> # unrestricted looping is equivalent to iterating over the entire Dataset
2617 >>> for q in ds: # doctest: +SKIP
2618 ... print(q) # doctest: +NORMALIZE_WHITESPACE
2619 (rdflib.term.URIRef("http://example.org/a"),
2620 rdflib.term.URIRef("http://www.example.org/b"),
2621 rdflib.term.Literal("foo"),
2622 None)
2623 (rdflib.term.URIRef("http://example.org/x"),
2624 rdflib.term.URIRef("http://example.org/y"),
2625 rdflib.term.Literal("bar"),
2626 rdflib.term.URIRef("http://www.example.com/gr"))
2627 (rdflib.term.URIRef("http://example.org/x"),
2628 rdflib.term.URIRef("http://example.org/z"),
2629 rdflib.term.Literal("foo-bar"),
2630 rdflib.term.URIRef("http://www.example.com/gr"))
2631
2632 >>> # resticting iteration to a graph:
2633 >>> for q in ds.quads((None, None, None, g)): # doctest: +SKIP
2634 ... print(q) # doctest: +NORMALIZE_WHITESPACE
2635 (rdflib.term.URIRef("http://example.org/x"),
2636 rdflib.term.URIRef("http://example.org/y"),
2637 rdflib.term.Literal("bar"),
2638 rdflib.term.URIRef("http://www.example.com/gr"))
2639 (rdflib.term.URIRef("http://example.org/x"),
2640 rdflib.term.URIRef("http://example.org/z"),
2641 rdflib.term.Literal("foo-bar"),
2642 rdflib.term.URIRef("http://www.example.com/gr"))
2643 >>> # Note that in the call above -
2644 >>> # ds.quads((None,None,None,"http://www.example.com/gr"))
2645 >>> # would have been accepted, too
2646
2647 >>> # graph names in the dataset can be queried:
2648 >>> for c in ds.graphs(): # doctest: +SKIP
2649 ... print(c.identifier) # doctest:
2650 urn:x-rdflib:default
2651 http://www.example.com/gr
2652 >>> # A graph can be created without specifying a name; a skolemized genid
2653 >>> # is created on the fly
2654 >>> h = ds.graph()
2655 >>> for c in ds.graphs(): # doctest: +SKIP
2656 ... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
2657 DEFAULT
2658 https://rdflib.github.io/.well-known/genid/rdflib/N...
2659 http://www.example.com/gr
2660 >>> # Note that the Dataset.graphs() call returns names of empty graphs,
2661 >>> # too. This can be restricted:
2662 >>> for c in ds.graphs(empty=False): # doctest: +SKIP
2663 ... print(c) # doctest: +NORMALIZE_WHITESPACE
2664 DEFAULT
2665 http://www.example.com/gr
2666
2667 >>> # a graph can also be removed from a dataset via ds.remove_graph(g)
2668 ```
2669
2670 !!! example "New in version 4.0"
2671 """
2672
2673 def __init__(
2674 self,
2675 store: Union[Store, str] = "default",
2676 default_union: bool = False,
2677 default_graph_base: Optional[str] = None,
2678 ):
2679 super(Dataset, self).__init__(store=store, identifier=None)
2680
2681 if not self.store.graph_aware:
2682 raise Exception("Dataset must be backed by a graph-aware store!")
2683 self._default_context = Graph(
2684 store=self.store,
2685 identifier=DATASET_DEFAULT_GRAPH_ID,
2686 base=default_graph_base,
2687 )
2688
2689 self.default_union = default_union
2690
2691 @property
2692 def default_context(self):
2693 warnings.warn(
2694 "Dataset.default_context is deprecated, use Dataset.default_graph instead.",
2695 DeprecationWarning,
2696 stacklevel=2,
2697 )
2698 return self._default_context
2699
2700 @default_context.setter
2701 def default_context(self, value):
2702 warnings.warn(
2703 "Dataset.default_context is deprecated, use Dataset.default_graph instead.",
2704 DeprecationWarning,
2705 stacklevel=2,
2706 )
2707 self._default_context = value
2708
2709 @property
2710 def default_graph(self):
2711 return self._default_context
2712
2713 @default_graph.setter
2714 def default_graph(self, value):
2715 self._default_context = value
2716
2717 @property
2718 def identifier(self):
2719 warnings.warn(
2720 "Dataset.identifier is deprecated and will be removed in future versions.",
2721 DeprecationWarning,
2722 stacklevel=2,
2723 )
2724 return super(Dataset, self).identifier
2725
2726 def __str__(self) -> str:
2727 pattern = (
2728 "[a rdflib:Dataset;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]"
2729 )
2730 return pattern % self.store.__class__.__name__
2731
2732 # type error: Return type "Tuple[Type[Dataset], Tuple[Store, bool]]" of "__reduce__" incompatible with return type "Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]" in supertype "ConjunctiveGraph"
2733 # type error: Return type "Tuple[Type[Dataset], Tuple[Store, bool]]" of "__reduce__" incompatible with return type "Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]" in supertype "Graph"
2734 def __reduce__(self) -> Tuple[Type[Dataset], Tuple[Store, bool]]: # type: ignore[override]
2735 return (type(self), (self.store, self.default_union))
2736
2737 def __getstate__(self) -> Tuple[Store, _ContextIdentifierType, _ContextType, bool]:
2738 return self.store, self.identifier, self.default_graph, self.default_union
2739
2740 def __setstate__(
2741 self, state: Tuple[Store, _ContextIdentifierType, _ContextType, bool]
2742 ) -> None:
2743 # type error: Property "store" defined in "Graph" is read-only
2744 # type error: Property "identifier" defined in "Graph" is read-only
2745 self.store, self.identifier, self.default_graph, self.default_union = state # type: ignore[misc]
2746
2747 def __iadd__(self: _DatasetT, other: Iterable[_QuadType]) -> _DatasetT: # type: ignore[override, misc]
2748 """Add all quads in Dataset other to Dataset.
2749 BNode IDs are not changed."""
2750 self.addN((s, p, o, g) for s, p, o, g in other)
2751 return self
2752
2753 def graph(
2754 self,
2755 identifier: Optional[Union[_ContextIdentifierType, _ContextType, str]] = None,
2756 base: Optional[str] = None,
2757 ) -> Graph:
2758 if identifier is None:
2759 from rdflib.term import _SKOLEM_DEFAULT_AUTHORITY, rdflib_skolem_genid
2760
2761 self.bind(
2762 "genid",
2763 _SKOLEM_DEFAULT_AUTHORITY + rdflib_skolem_genid,
2764 override=False,
2765 )
2766 identifier = BNode().skolemize()
2767
2768 graph_to_copy: Optional[Graph] = None
2769 if isinstance(identifier, Graph) and not isinstance(
2770 identifier, (Dataset, ConjunctiveGraph)
2771 ):
2772 # Preserve #3259 semantics: importing an external graph through
2773 # Dataset.graph()/add_graph() should copy its statements.
2774 graph_to_copy = identifier
2775
2776 g = self._graph(identifier)
2777 if graph_to_copy is not None:
2778 g.__iadd__(graph_to_copy)
2779 g.base = base
2780
2781 self.store.add_graph(g)
2782 return g
2783
2784 def parse(
2785 self,
2786 source: Optional[
2787 Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
2788 ] = None,
2789 publicID: Optional[str] = None, # noqa: N803
2790 format: Optional[str] = None,
2791 location: Optional[str] = None,
2792 file: Optional[Union[BinaryIO, TextIO]] = None,
2793 data: Optional[Union[str, bytes]] = None,
2794 **args: Any,
2795 ) -> Dataset:
2796 """Parse an RDF source adding the resulting triples to the Graph.
2797
2798 Args:
2799 source: The source to parse. See rdflib.graph.Graph.parse for details.
2800 publicID: The public ID of the source.
2801 format: The format of the source.
2802 location: The location of the source.
2803 file: The file object to parse.
2804 data: The data to parse.
2805 **args: Additional arguments.
2806
2807 Returns:
2808 The graph that the source was parsed into.
2809
2810 Note:
2811 The source is specified using one of source, location, file or data.
2812
2813 If the source is in a format that does not support named graphs its triples
2814 will be added to the default graph
2815 (i.e. :attr:`.Dataset.default_graph`).
2816 If the source is in a format that does not support named graphs its triples
2817 will be added to the default graph (i.e. Dataset.default_graph).
2818
2819 !!! warning "Caution"
2820 This method can access directly or indirectly requested network or
2821 file resources, for example, when parsing JSON-LD documents with
2822 `@context` directives that point to a network location.
2823
2824 When processing untrusted or potentially malicious documents,
2825 measures should be taken to restrict network and file access.
2826
2827 For information on available security measures, see the RDFLib
2828 Security Considerations documentation.
2829
2830 !!! example "Changed in 7.0"
2831 The `publicID` argument is no longer used as the identifier (i.e. name)
2832 of the default graph as was the case before version 7.0. In the case of
2833 sources that do not support named graphs, the `publicID` parameter will
2834 also not be used as the name for the graph that the data is loaded into,
2835 and instead the triples from sources that do not support named graphs will
2836 be loaded into the default graph (i.e. Dataset.default_graph).
2837 """
2838
2839 ConjunctiveGraph.parse(
2840 self, source, publicID, format, location, file, data, **args
2841 )
2842 return self
2843
2844 def add_graph(
2845 self, g: Optional[Union[_ContextIdentifierType, _ContextType, str]]
2846 ) -> Graph:
2847 """alias of graph for consistency"""
2848 return self.graph(g)
2849
2850 def remove_graph(
2851 self: _DatasetT, g: Optional[Union[_ContextIdentifierType, _ContextType, str]]
2852 ) -> _DatasetT:
2853 if not isinstance(g, Graph):
2854 g = self.get_context(g)
2855
2856 self.store.remove_graph(g)
2857 if g is None or g == self.default_graph:
2858 # default graph cannot be removed
2859 # only triples deleted, so add it back in
2860 self.store.add_graph(self.default_graph)
2861 return self
2862
2863 def contexts(
2864 self, triple: Optional[_TripleType] = None
2865 ) -> Generator[_ContextType, None, None]:
2866 warnings.warn(
2867 "Dataset.contexts is deprecated, use Dataset.graphs instead.",
2868 DeprecationWarning,
2869 stacklevel=2,
2870 )
2871 default = False
2872 for c in super(Dataset, self).contexts(triple):
2873 default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
2874 yield c
2875 if not default:
2876 yield self.graph(DATASET_DEFAULT_GRAPH_ID)
2877
2878 def graphs(
2879 self, triple: Optional[_TripleType] = None
2880 ) -> Generator[_ContextType, None, None]:
2881 default = False
2882 for c in super(Dataset, self).contexts(triple):
2883 default |= c.identifier == DATASET_DEFAULT_GRAPH_ID
2884 yield c
2885 if not default:
2886 yield self.graph(DATASET_DEFAULT_GRAPH_ID)
2887
2888 # type error: Return type "Generator[Tuple[Node, Node, Node, Optional[Node]], None, None]" of "quads" incompatible with return type "Generator[Tuple[Node, Node, Node, Optional[Graph]], None, None]" in supertype "ConjunctiveGraph"
2889 def quads( # type: ignore[override]
2890 self, quad: Optional[_TripleOrQuadPatternType] = None
2891 ) -> Generator[_OptionalIdentifiedQuadType, None, None]:
2892 for s, p, o, c in super(Dataset, self).quads(quad):
2893 # type error: Item "None" of "Optional[Graph]" has no attribute "identifier"
2894 if c.identifier == self.default_graph: # type: ignore[union-attr]
2895 yield s, p, o, None
2896 else:
2897 # type error: Item "None" of "Optional[Graph]" has no attribute "identifier" [union-attr]
2898 yield s, p, o, c.identifier # type: ignore[union-attr]
2899
2900 # type error: Return type "Generator[Tuple[Node, URIRef, Node, Optional[IdentifiedNode]], None, None]" of "__iter__" incompatible with return type "Generator[Tuple[IdentifiedNode, IdentifiedNode, Union[IdentifiedNode, Literal]], None, None]" in supertype "Graph"
2901 def __iter__( # type: ignore[override]
2902 self,
2903 ) -> Generator[_OptionalIdentifiedQuadType, None, None]:
2904 """Iterates over all quads in the store"""
2905 return self.quads((None, None, None, None))
2906
2907 @overload
2908 def serialize(
2909 self,
2910 destination: None,
2911 format: str,
2912 base: Optional[str],
2913 encoding: str,
2914 **args: Any,
2915 ) -> bytes: ...
2916
2917 # no destination and non-None keyword encoding
2918 @overload
2919 def serialize(
2920 self,
2921 destination: None = ...,
2922 format: str = ...,
2923 base: Optional[str] = ...,
2924 *,
2925 encoding: str,
2926 **args: Any,
2927 ) -> bytes: ...
2928
2929 # no destination and None encoding
2930 @overload
2931 def serialize(
2932 self,
2933 destination: None = ...,
2934 format: str = ...,
2935 base: Optional[str] = ...,
2936 encoding: None = ...,
2937 **args: Any,
2938 ) -> str: ...
2939
2940 # non-None destination
2941 @overload
2942 def serialize(
2943 self,
2944 destination: Union[str, pathlib.PurePath, IO[bytes]],
2945 format: str = ...,
2946 base: Optional[str] = ...,
2947 encoding: Optional[str] = ...,
2948 **args: Any,
2949 ) -> Graph: ...
2950
2951 # fallback
2952 @overload
2953 def serialize(
2954 self,
2955 destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = ...,
2956 format: str = ...,
2957 base: Optional[str] = ...,
2958 encoding: Optional[str] = ...,
2959 **args: Any,
2960 ) -> Union[bytes, str, Graph]: ...
2961
2962 def serialize(
2963 self,
2964 destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None,
2965 format: str = "trig",
2966 base: Optional[str] = None,
2967 encoding: Optional[str] = None,
2968 **args: Any,
2969 ) -> Union[bytes, str, Graph]:
2970 return super(Dataset, self).serialize(
2971 destination=destination, format=format, base=base, encoding=encoding, **args
2972 )
2973
2974
2975class QuotedGraph(Graph):
2976 """
2977 Quoted Graphs are intended to implement Notation 3 formulae. They are
2978 associated with a required identifier that the N3 parser *must* provide
2979 in order to maintain consistent formulae identification for scenarios
2980 such as implication and other such processing.
2981 """
2982
2983 def __init__(
2984 self,
2985 store: Union[Store, str],
2986 identifier: Optional[Union[_ContextIdentifierType, str]],
2987 ):
2988 super(QuotedGraph, self).__init__(store, identifier)
2989
2990 def add(self: _GraphT, triple: _TripleType) -> _GraphT:
2991 """Add a triple with self as context"""
2992 s, p, o = triple
2993 assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,)
2994 assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,)
2995 assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,)
2996
2997 self.store.add((s, p, o), self, quoted=True)
2998 return self
2999
3000 def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT: # noqa: N802
3001 """Add a sequence of triple with context"""
3002
3003 self.store.addN(
3004 (s, p, o, c)
3005 for s, p, o, c in quads
3006 if isinstance(c, QuotedGraph)
3007 and c.identifier is self.identifier
3008 and _assertnode(s, p, o)
3009 )
3010 return self
3011
3012 def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str:
3013 """Return an n3 identifier for the Graph"""
3014 return "{%s}" % self.identifier.n3(namespace_manager=namespace_manager)
3015
3016 def __str__(self) -> str:
3017 identifier = self.identifier.n3()
3018 label = self.store.__class__.__name__
3019 pattern = (
3020 "{this rdflib.identifier %s;rdflib:storage "
3021 "[a rdflib:Store;rdfs:label '%s']}"
3022 )
3023 return pattern % (identifier, label)
3024
3025 def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]:
3026 return QuotedGraph, (self.store, self.identifier)
3027
3028
3029# Make sure QuotedGraph is ordered correctly
3030# wrt to other Terms.
3031# this must be done here, as the QuotedGraph cannot be
3032# circularily imported in term.py
3033rdflib.term._ORDERING[QuotedGraph] = 11
3034
3035
3036class Seq:
3037 """Wrapper around an RDF Seq resource
3038
3039 It implements a container type in Python with the order of the items
3040 returned corresponding to the Seq content. It is based on the natural
3041 ordering of the predicate names _1, _2, _3, etc, which is the
3042 'implementation' of a sequence in RDF terms.
3043
3044 Args:
3045 graph: the graph containing the Seq
3046 subject:the subject of a Seq. Note that the init does not
3047 check whether this is a Seq, this is done in whoever
3048 creates this instance!
3049 """
3050
3051 def __init__(self, graph: Graph, subject: _SubjectType):
3052 self._list: List[Tuple[int, _ObjectType]]
3053 _list = self._list = list()
3054 LI_INDEX = URIRef(str(RDF) + "_") # noqa: N806
3055 for p, o in graph.predicate_objects(subject):
3056 # type error: "Node" has no attribute "startswith"
3057 if p.startswith(LI_INDEX): # type: ignore[attr-defined] # != RDF.Seq:
3058 # type error: "Node" has no attribute "replace"
3059 i = int(p.replace(LI_INDEX, "")) # type: ignore[attr-defined]
3060 _list.append((i, o))
3061
3062 # here is the trick: the predicates are _1, _2, _3, etc. Ie,
3063 # by sorting the keys (by integer) we have what we want!
3064 _list.sort()
3065
3066 def toPython(self) -> Seq: # noqa: N802
3067 return self
3068
3069 def __iter__(self) -> Generator[_ObjectType, None, None]:
3070 """Generator over the items in the Seq"""
3071 for _, item in self._list:
3072 yield item
3073
3074 def __len__(self) -> int:
3075 """Length of the Seq"""
3076 return len(self._list)
3077
3078 def __getitem__(self, index) -> _ObjectType:
3079 """Item given by index from the Seq"""
3080 index, item = self._list.__getitem__(index)
3081 return item
3082
3083
3084class ModificationException(Exception): # noqa: N818
3085 def __init__(self) -> None:
3086 pass
3087
3088 def __str__(self) -> str:
3089 return (
3090 "Modifications and transactional operations not allowed on "
3091 "ReadOnlyGraphAggregate instances"
3092 )
3093
3094
3095class UnSupportedAggregateOperation(Exception): # noqa: N818
3096 def __init__(self) -> None:
3097 pass
3098
3099 def __str__(self) -> str:
3100 return "This operation is not supported by ReadOnlyGraphAggregate " "instances"
3101
3102
3103class ReadOnlyGraphAggregate(ConjunctiveGraph):
3104 """Utility class for treating a set of graphs as a single graph
3105
3106 Only read operations are supported (hence the name). Essentially a
3107 ConjunctiveGraph over an explicit subset of the entire store.
3108 """
3109
3110 def __init__(self, graphs: List[Graph], store: Union[str, Store] = "default"):
3111 if store is not None:
3112 super(ReadOnlyGraphAggregate, self).__init__(store)
3113 Graph.__init__(self, store)
3114 self.__namespace_manager = None
3115
3116 assert (
3117 isinstance(graphs, list)
3118 and graphs
3119 and [g for g in graphs if isinstance(g, Graph)]
3120 ), "graphs argument must be a list of Graphs!!"
3121 self.graphs = graphs
3122
3123 def __repr__(self) -> str:
3124 return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs)
3125
3126 def destroy(self, configuration: str) -> NoReturn:
3127 raise ModificationException()
3128
3129 # Transactional interfaces (optional)
3130 def commit(self) -> NoReturn:
3131 raise ModificationException()
3132
3133 def rollback(self) -> NoReturn:
3134 raise ModificationException()
3135
3136 def open(self, configuration: str | tuple[str, str], create: bool = False) -> None:
3137 # TODO: is there a use case for this method?
3138 for graph in self.graphs:
3139 # type error: Too many arguments for "open" of "Graph"
3140 # type error: Argument 1 to "open" of "Graph" has incompatible type "ReadOnlyGraphAggregate"; expected "str" [arg-type]
3141 # type error: Argument 2 to "open" of "Graph" has incompatible type "str"; expected "bool" [arg-type]
3142 graph.open(self, configuration, create) # type: ignore[call-arg, arg-type]
3143
3144 # type error: Signature of "close" incompatible with supertype "Graph"
3145 def close(self) -> None: # type: ignore[override]
3146 for graph in self.graphs:
3147 graph.close()
3148
3149 def add(self, triple: _TripleOrOptionalQuadType) -> NoReturn:
3150 raise ModificationException()
3151
3152 def addN(self, quads: Iterable[_QuadType]) -> NoReturn: # noqa: N802
3153 raise ModificationException()
3154
3155 # type error: Argument 1 of "remove" is incompatible with supertype "Graph"; supertype defines the argument type as "Tuple[Optional[Node], Optional[Node], Optional[Node]]"
3156 def remove(self, triple: _TripleOrOptionalQuadType) -> NoReturn: # type: ignore[override]
3157 raise ModificationException()
3158
3159 # type error: Signature of "triples" incompatible with supertype "ConjunctiveGraph"
3160 @overload # type: ignore[override]
3161 def triples(
3162 self,
3163 triple: _TriplePatternType,
3164 ) -> Generator[_TripleType, None, None]: ...
3165
3166 @overload
3167 def triples(
3168 self,
3169 triple: _TriplePathPatternType,
3170 ) -> Generator[_TriplePathType, None, None]: ...
3171
3172 @overload
3173 def triples(
3174 self,
3175 triple: _TripleSelectorType,
3176 ) -> Generator[_TripleOrTriplePathType, None, None]: ...
3177
3178 def triples(
3179 self,
3180 triple: _TripleSelectorType,
3181 ) -> Generator[_TripleOrTriplePathType, None, None]:
3182 s, p, o = triple
3183 for graph in self.graphs:
3184 if isinstance(p, Path):
3185 for s, o in p.eval(self, s, o):
3186 yield s, p, o
3187 else:
3188 for s1, p1, o1 in graph.triples((s, p, o)):
3189 yield s1, p1, o1
3190
3191 def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool:
3192 context = None
3193 if len(triple_or_quad) == 4:
3194 # type error: Tuple index out of range
3195 context = triple_or_quad[3] # type: ignore [misc, unused-ignore]
3196 for graph in self.graphs:
3197 if context is None or graph.identifier == context.identifier:
3198 if triple_or_quad[:3] in graph:
3199 return True
3200 return False
3201
3202 # type error: Signature of "quads" incompatible with supertype "ConjunctiveGraph"
3203 def quads( # type: ignore[override]
3204 self, triple_or_quad: _TripleOrQuadSelectorType
3205 ) -> Generator[
3206 Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType],
3207 None,
3208 None,
3209 ]:
3210 """Iterate over all the quads in the entire aggregate graph"""
3211 c = None
3212 if len(triple_or_quad) == 4:
3213 # type error: Need more than 3 values to unpack (4 expected)
3214 s, p, o, c = triple_or_quad # type: ignore[misc, unused-ignore]
3215 else:
3216 # type error: Too many values to unpack (3 expected, 4 provided)
3217 s, p, o = triple_or_quad # type: ignore[misc, unused-ignore]
3218
3219 if c is not None:
3220 for graph in [g for g in self.graphs if g == c]:
3221 for s1, p1, o1 in graph.triples((s, p, o)):
3222 yield s1, p1, o1, graph
3223 else:
3224 for graph in self.graphs:
3225 for s1, p1, o1 in graph.triples((s, p, o)):
3226 yield s1, p1, o1, graph
3227
3228 def __len__(self) -> int:
3229 return sum(len(g) for g in self.graphs)
3230
3231 def __hash__(self) -> NoReturn:
3232 raise UnSupportedAggregateOperation()
3233
3234 def __cmp__(self, other) -> int:
3235 if other is None:
3236 return -1
3237 elif isinstance(other, Graph):
3238 return -1
3239 elif isinstance(other, ReadOnlyGraphAggregate):
3240 return (self.graphs > other.graphs) - (self.graphs < other.graphs)
3241 else:
3242 return -1
3243
3244 def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn:
3245 raise ModificationException()
3246
3247 def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn:
3248 raise ModificationException()
3249
3250 # Conv. methods
3251
3252 def triples_choices(
3253 self,
3254 triple: _TripleChoiceType,
3255 context: Optional[_ContextType] = None,
3256 ) -> Generator[_TripleType, None, None]:
3257 subject, predicate, object_ = triple
3258 for graph in self.graphs:
3259 # 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]]]"
3260 # type error note: unpacking discards type info
3261 choices = graph.triples_choices((subject, predicate, object_)) # type: ignore[arg-type]
3262 for s, p, o in choices:
3263 yield s, p, o
3264
3265 def qname(self, uri: str) -> str:
3266 if hasattr(self, "namespace_manager") and self.namespace_manager:
3267 return self.namespace_manager.qname(uri)
3268 raise UnSupportedAggregateOperation()
3269
3270 def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
3271 if hasattr(self, "namespace_manager") and self.namespace_manager:
3272 return self.namespace_manager.compute_qname(uri, generate)
3273 raise UnSupportedAggregateOperation()
3274
3275 # type error: Signature of "bind" incompatible with supertype "Graph"
3276 def bind( # type: ignore[override]
3277 self, prefix: Optional[str], namespace: Any, override: bool = True # noqa: F811
3278 ) -> NoReturn:
3279 raise UnSupportedAggregateOperation()
3280
3281 def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]:
3282 if hasattr(self, "namespace_manager"):
3283 for prefix, namespace in self.namespace_manager.namespaces():
3284 yield prefix, namespace
3285 else:
3286 for graph in self.graphs:
3287 for prefix, namespace in graph.namespaces():
3288 yield prefix, namespace
3289
3290 def absolutize(self, uri: str, defrag: int = 1) -> NoReturn:
3291 raise UnSupportedAggregateOperation()
3292
3293 # type error: Signature of "parse" incompatible with supertype "ConjunctiveGraph"
3294 def parse( # type: ignore[override]
3295 self,
3296 source: Optional[
3297 Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
3298 ],
3299 publicID: Optional[str] = None, # noqa: N803
3300 format: Optional[str] = None,
3301 **args: Any,
3302 ) -> NoReturn:
3303 raise ModificationException()
3304
3305 def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> NoReturn:
3306 raise UnSupportedAggregateOperation()
3307
3308 def __reduce__(self) -> NoReturn:
3309 raise UnSupportedAggregateOperation()
3310
3311
3312@overload
3313def _assertnode(*terms: Node) -> te.Literal[True]: ...
3314
3315
3316@overload
3317def _assertnode(*terms: Any) -> bool: ...
3318
3319
3320def _assertnode(*terms: Any) -> bool:
3321 for t in terms:
3322 assert isinstance(t, Node), "Term %s must be an rdflib term" % (t,)
3323 return True
3324
3325
3326class BatchAddGraph:
3327 """Wrapper around graph that turns batches of calls to Graph's add
3328 (and optionally, addN) into calls to batched calls to addN`.
3329
3330 Args:
3331 graph: The graph to wrap
3332 batch_size: The maximum number of triples to buffer before passing to
3333 Graph's addN
3334 batch_addn: If True, then even calls to `addN` will be batched according to
3335 batch_size
3336
3337 Attributes:
3338 graph: The wrapped graph
3339 count: The number of triples buffered since initialization or the last call to reset
3340 batch: The current buffer of triples
3341 """
3342
3343 def __init__(self, graph: Graph, batch_size: int = 1000, batch_addn: bool = False):
3344 if not batch_size or batch_size < 2:
3345 raise ValueError("batch_size must be a positive number")
3346 self.graph = graph
3347 self.__graph_tuple = (graph,)
3348 self.__batch_size = batch_size
3349 self.__batch_addn = batch_addn
3350 self.reset()
3351
3352 def reset(self) -> BatchAddGraph:
3353 """
3354 Manually clear the buffered triples and reset the count to zero
3355 """
3356 self.batch: List[_QuadType] = []
3357 self.count = 0
3358 return self
3359
3360 def add(
3361 self,
3362 triple_or_quad: Union[
3363 _TripleType,
3364 _QuadType,
3365 ],
3366 ) -> BatchAddGraph:
3367 """Add a triple to the buffer.
3368
3369 Args:
3370 triple_or_quad: The triple or quad to add
3371
3372 Returns:
3373 The BatchAddGraph instance
3374 """
3375 if len(self.batch) >= self.__batch_size:
3376 self.graph.addN(self.batch)
3377 self.batch = []
3378 self.count += 1
3379 if len(triple_or_quad) == 3:
3380 # type error: Argument 1 to "append" of "list" has incompatible type "Tuple[Node, ...]"; expected "Tuple[Node, Node, Node, Graph]"
3381 self.batch.append(triple_or_quad + self.__graph_tuple) # type: ignore[arg-type, unused-ignore]
3382 else:
3383 # 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]"
3384 self.batch.append(triple_or_quad) # type: ignore[arg-type, unused-ignore]
3385 return self
3386
3387 def addN(self, quads: Iterable[_QuadType]) -> BatchAddGraph: # noqa: N802
3388 if self.__batch_addn:
3389 for q in quads:
3390 self.add(q)
3391 else:
3392 self.graph.addN(quads)
3393 return self
3394
3395 def __enter__(self) -> BatchAddGraph:
3396 self.reset()
3397 return self
3398
3399 def __exit__(self, *exc) -> None:
3400 if exc[0] is None:
3401 self.graph.addN(self.batch)