-
Notifications
You must be signed in to change notification settings - Fork 543
/
graph.py
3000 lines (2552 loc) · 108 KB
/
graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
import pathlib
import random
from io import BytesIO
from typing import (
IO,
TYPE_CHECKING,
Any,
BinaryIO,
Callable,
Dict,
Generator,
Iterable,
List,
Mapping,
NoReturn,
Optional,
Set,
TextIO,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
from urllib.parse import urlparse
from urllib.request import url2pathname
import rdflib.exceptions as exceptions
import rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.
import rdflib.plugin as plugin
import rdflib.query as query
import rdflib.util # avoid circular dependency
from rdflib.collection import Collection
from rdflib.exceptions import ParserError
from rdflib.namespace import RDF, Namespace, NamespaceManager
from rdflib.parser import InputSource, Parser, create_input_source
from rdflib.paths import Path
from rdflib.resource import Resource
from rdflib.serializer import Serializer
from rdflib.store import Store
from rdflib.term import (
BNode,
Genid,
IdentifiedNode,
Identifier,
Literal,
Node,
RDFLibGenid,
URIRef,
)
if TYPE_CHECKING:
import typing_extensions as te
import rdflib.query
from rdflib.plugins.sparql.sparql import Query, Update
_SubjectType = Node
_PredicateType = Node
_ObjectType = Node
_ContextIdentifierType = IdentifiedNode
_TripleType = Tuple["_SubjectType", "_PredicateType", "_ObjectType"]
_QuadType = Tuple["_SubjectType", "_PredicateType", "_ObjectType", "_ContextType"]
_OptionalQuadType = Tuple[
"_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextType"]
]
_TripleOrOptionalQuadType = Union["_TripleType", "_OptionalQuadType"]
_OptionalIdentifiedQuadType = Tuple[
"_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextIdentifierType"]
]
_TriplePatternType = Tuple[
Optional["_SubjectType"], Optional["_PredicateType"], Optional["_ObjectType"]
]
_TriplePathPatternType = Tuple[Optional["_SubjectType"], Path, Optional["_ObjectType"]]
_QuadPatternType = Tuple[
Optional["_SubjectType"],
Optional["_PredicateType"],
Optional["_ObjectType"],
Optional["_ContextType"],
]
_QuadPathPatternType = Tuple[
Optional["_SubjectType"],
Path,
Optional["_ObjectType"],
Optional["_ContextType"],
]
_TripleOrQuadPatternType = Union["_TriplePatternType", "_QuadPatternType"]
_TripleOrQuadPathPatternType = Union["_TriplePathPatternType", "_QuadPathPatternType"]
_TripleSelectorType = Tuple[
Optional["_SubjectType"],
Optional[Union["Path", "_PredicateType"]],
Optional["_ObjectType"],
]
_QuadSelectorType = Tuple[
Optional["_SubjectType"],
Optional[Union["Path", "_PredicateType"]],
Optional["_ObjectType"],
Optional["_ContextType"],
]
_TripleOrQuadSelectorType = Union["_TripleSelectorType", "_QuadSelectorType"]
_TriplePathType = Tuple["_SubjectType", Path, "_ObjectType"]
_TripleOrTriplePathType = Union["_TripleType", "_TriplePathType"]
_GraphT = TypeVar("_GraphT", bound="Graph")
_ConjunctiveGraphT = TypeVar("_ConjunctiveGraphT", bound="ConjunctiveGraph")
_DatasetT = TypeVar("_DatasetT", bound="Dataset")
# type error: Function "Type[Literal]" could always be true in boolean contex
assert Literal # type: ignore[truthy-function] # avoid warning
# type error: Function "Type[Namespace]" could always be true in boolean context
assert Namespace # type: ignore[truthy-function] # avoid warning
if TYPE_CHECKING:
from rdflib._type_checking import _NamespaceSetString
logger = logging.getLogger(__name__)
__doc__ = """\
RDFLib defines the following kinds of Graphs:
* :class:`~rdflib.graph.Graph`
* :class:`~rdflib.graph.QuotedGraph`
* :class:`~rdflib.graph.ConjunctiveGraph`
* :class:`~rdflib.graph.Dataset`
Graph
-----
An RDF graph is a set of RDF triples. Graphs support the python ``in``
operator, as well as iteration and some operations like union,
difference and intersection.
see :class:`~rdflib.graph.Graph`
Conjunctive Graph
-----------------
A Conjunctive Graph is the most relevant collection of graphs that are
considered to be the boundary for closed world assumptions. This
boundary is equivalent to that of the store instance (which is itself
uniquely identified and distinct from other instances of
:class:`~rdflib.store.Store` that signify other Conjunctive Graphs). It is
equivalent to all the named graphs within it and associated with a
``_default_`` graph which is automatically assigned a
:class:`~rdflib.term.BNode` for an identifier - if one isn't given.
see :class:`~rdflib.graph.ConjunctiveGraph`
Quoted graph
------------
The notion of an RDF graph [14] is extended to include the concept of
a formula node. A formula node may occur wherever any other kind of
node can appear. Associated with a formula node is an RDF graph that
is completely disjoint from all other graphs; i.e. has no nodes in
common with any other graph. (It may contain the same labels as other
RDF graphs; because this is, by definition, a separate graph,
considerations of tidiness do not apply between the graph at a formula
node and any other graph.)
This is intended to map the idea of "{ N3-expression }" that is used
by N3 into an RDF graph upon which RDF semantics is defined.
see :class:`~rdflib.graph.QuotedGraph`
Dataset
-------
The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The
primary term is "graphs in the datasets" and not "contexts with quads"
so there is a separate method to set/retrieve a graph in a dataset and
to operate with dataset graphs. As a consequence of this approach,
dataset graphs cannot be identified with blank nodes, a name is always
required (RDFLib will automatically add a name if one is not provided
at creation time). This implementation includes a convenience method
to directly add a single quad to a dataset graph.
see :class:`~rdflib.graph.Dataset`
Working with graphs
===================
Instantiating Graphs with default store (Memory) and default identifier
(a BNode):
>>> g = Graph()
>>> g.store.__class__
<class 'rdflib.plugins.stores.memory.Memory'>
>>> g.identifier.__class__
<class 'rdflib.term.BNode'>
Instantiating Graphs with a Memory store and an identifier -
<https://rdflib.github.io>:
>>> g = Graph('Memory', URIRef("https://rdflib.github.io"))
>>> g.identifier
rdflib.term.URIRef('https://rdflib.github.io')
>>> str(g) # doctest: +NORMALIZE_WHITESPACE
"<https://rdflib.github.io> a rdfg:Graph;rdflib:storage
[a rdflib:Store;rdfs:label 'Memory']."
Creating a ConjunctiveGraph - The top level container for all named Graphs
in a "database":
>>> g = ConjunctiveGraph()
>>> str(g.default_context)
"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']]."
Adding / removing reified triples to Graph and iterating over it directly or
via triple pattern:
>>> g = Graph()
>>> statementId = BNode()
>>> print(len(g))
0
>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.subject,
... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
4
>>> for s, p, o in g:
... print(type(s))
...
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
<class 'rdflib.term.BNode'>
>>> for s, p, o in g.triples((None, RDF.object, None)):
... print(o)
...
Conjunctive Graph
>>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> print(len(g))
3
``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be
thought of as "open variables".
Graph support set-theoretic operators, you can add/subtract graphs, as
well as intersection (with multiplication operator g1*g2) and xor (g1
^ g2).
Note that BNode IDs are kept when doing set-theoretic operations, this
may or may not be what you want. Two named graphs within the same
application probably want share BNode IDs, two graphs with data from
different sources probably not. If your BNode IDs are all generated
by RDFLib they are UUIDs and unique.
>>> g1 = Graph()
>>> g2 = Graph()
>>> u = URIRef("http://example.com/foo")
>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(g1 + g2) # adds bing as label
3
>>> len(g1 - g2) # removes foo
1
>>> len(g1 * g2) # only foo
1
>>> g1 += g2 # now g1 contains everything
Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within
the same store:
>>> store = plugin.get("Memory", Store)()
>>> g1 = Graph(store)
>>> g2 = Graph(store)
>>> g3 = Graph(store)
>>> stmt1 = BNode()
>>> stmt2 = BNode()
>>> stmt3 = BNode()
>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.subject,
... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> g3.add((stmt3, RDF.object, Literal(
... 'The top-level aggregate graph - The sum ' +
... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))
3
>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(
... RDF.type, RDF.Statement)))
2
ConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method
which returns quads instead of triples, where the fourth item is the Graph
(or subclass thereof) instance in which the triple was asserted:
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store
... ).quads((None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
3
>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])
>>> uniqueGraphNames = set(
... [graph.identifier for s, p, o, graph in unionGraph.quads(
... (None, RDF.predicate, None))])
>>> len(uniqueGraphNames)
2
Parsing N3 from a string
>>> g2 = Graph()
>>> src = '''
... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
... [ a rdf:Statement ;
... rdf:subject <https://rdflib.github.io/store#ConjunctiveGraph>;
... rdf:predicate rdfs:label;
... rdf:object "Conjunctive Graph" ] .
... '''
>>> g2 = g2.parse(data=src, format="n3")
>>> print(len(g2))
4
Using Namespace class:
>>> RDFLib = Namespace("https://rdflib.github.io/")
>>> RDFLib.ConjunctiveGraph
rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')
>>> RDFLib["Graph"]
rdflib.term.URIRef('https://rdflib.github.io/Graph')
"""
__all__ = [
"Graph",
"ConjunctiveGraph",
"QuotedGraph",
"Seq",
"ModificationException",
"Dataset",
"UnSupportedAggregateOperation",
"ReadOnlyGraphAggregate",
"BatchAddGraph",
"_ConjunctiveGraphT",
"_ContextIdentifierType",
"_DatasetT",
"_GraphT",
"_ObjectType",
"_OptionalIdentifiedQuadType",
"_OptionalQuadType",
"_PredicateType",
"_QuadPathPatternType",
"_QuadPatternType",
"_QuadSelectorType",
"_QuadType",
"_SubjectType",
"_TripleOrOptionalQuadType",
"_TripleOrTriplePathType",
"_TripleOrQuadPathPatternType",
"_TripleOrQuadPatternType",
"_TripleOrQuadSelectorType",
"_TriplePathPatternType",
"_TriplePathType",
"_TriplePatternType",
"_TripleSelectorType",
"_TripleType",
]
# : Transitive closure arg type.
_TCArgT = TypeVar("_TCArgT")
class Graph(Node):
"""An RDF Graph
The constructor accepts one argument, the "store"
that will be used to store the graph data (see the "store"
package for stores currently shipped with rdflib).
Stores can be context-aware or unaware. Unaware stores take up
(some) less space but cannot support features that require
context, such as true merging/demerging of sub-graphs and
provenance.
Even if used with a context-aware store, Graph will only expose the quads which
belong to the default graph. To access the rest of the data, `ConjunctiveGraph` or
`Dataset` classes can be used instead.
The Graph constructor can take an identifier which identifies the Graph
by name. If none is given, the graph is assigned a BNode for its
identifier.
For more on named graphs, see: http://www.w3.org/2004/03/trix/
"""
def __init__(
self,
store: Union[Store, str] = "default",
identifier: Optional[Union[_ContextIdentifierType, str]] = None,
namespace_manager: Optional[NamespaceManager] = None,
base: Optional[str] = None,
bind_namespaces: "_NamespaceSetString" = "rdflib",
):
super(Graph, self).__init__()
self.base = base
self.__identifier: _ContextIdentifierType
self.__identifier = identifier or BNode() # type: ignore[assignment]
if not isinstance(self.__identifier, IdentifiedNode):
self.__identifier = URIRef(self.__identifier) # type: ignore[unreachable]
self.__store: Store
if not isinstance(store, Store):
# TODO: error handling
self.__store = store = plugin.get(store, Store)()
else:
self.__store = store
self.__namespace_manager = namespace_manager
self._bind_namespaces = bind_namespaces
self.context_aware = False
self.formula_aware = False
self.default_union = False
@property
def store(self) -> Store:
return self.__store
@property
def identifier(self) -> "_ContextIdentifierType":
return self.__identifier
@property
def namespace_manager(self) -> NamespaceManager:
"""
this graph's namespace-manager
"""
if self.__namespace_manager is None:
self.__namespace_manager = NamespaceManager(self, self._bind_namespaces)
return self.__namespace_manager
@namespace_manager.setter
def namespace_manager(self, nm: NamespaceManager) -> None:
self.__namespace_manager = nm
def __repr__(self) -> str:
return "<Graph identifier=%s (%s)>" % (self.identifier, type(self))
def __str__(self) -> str:
if isinstance(self.identifier, URIRef):
return (
"%s a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']."
) % (self.identifier.n3(), self.store.__class__.__name__)
else:
return (
"[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]."
) % self.store.__class__.__name__
def toPython(self: _GraphT) -> _GraphT: # noqa: N802
return self
def destroy(self: _GraphT, configuration: str) -> _GraphT:
"""Destroy the store identified by ``configuration`` if supported"""
self.__store.destroy(configuration)
return self
# Transactional interfaces (optional)
def commit(self: _GraphT) -> _GraphT:
"""Commits active transactions"""
self.__store.commit()
return self
def rollback(self: _GraphT) -> _GraphT:
"""Rollback active transactions"""
self.__store.rollback()
return self
def open(self, configuration: str, create: bool = False) -> Optional[int]:
"""Open the graph store
Might be necessary for stores that require opening a connection to a
database or acquiring some resource.
"""
return self.__store.open(configuration, create)
def close(self, commit_pending_transaction: bool = False) -> None:
"""Close the graph store
Might be necessary for stores that require closing a connection to a
database or releasing some resource.
"""
return self.__store.close(commit_pending_transaction=commit_pending_transaction)
def add(self: _GraphT, triple: "_TripleType") -> _GraphT:
"""Add a triple with self as context"""
s, p, o = triple
assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,)
assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,)
assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,)
self.__store.add((s, p, o), self, quoted=False)
return self
def addN(self: _GraphT, quads: Iterable["_QuadType"]) -> _GraphT: # noqa: N802
"""Add a sequence of triple with context"""
self.__store.addN(
(s, p, o, c)
for s, p, o, c in quads
if isinstance(c, Graph)
and c.identifier is self.identifier
and _assertnode(s, p, o)
)
return self
def remove(self: _GraphT, triple: "_TriplePatternType") -> _GraphT:
"""Remove a triple from the graph
If the triple does not provide a context attribute, removes the triple
from all contexts.
"""
self.__store.remove(triple, context=self)
return self
@overload
def triples(
self,
triple: "_TriplePatternType",
) -> Generator["_TripleType", None, None]:
...
@overload
def triples(
self,
triple: "_TriplePathPatternType",
) -> Generator["_TriplePathType", None, None]:
...
@overload
def triples(
self,
triple: "_TripleSelectorType",
) -> Generator["_TripleOrTriplePathType", None, None]:
...
def triples(
self,
triple: "_TripleSelectorType",
) -> Generator["_TripleOrTriplePathType", None, None]:
"""Generator over the triple store
Returns triples that match the given triple pattern. If triple pattern
does not provide a context, all contexts will be searched.
"""
s, p, o = triple
if isinstance(p, Path):
for _s, _o in p.eval(self, s, o):
yield _s, p, _o
else:
for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self):
yield _s, _p, _o
def __getitem__(self, item):
"""
A graph can be "sliced" as a shortcut for the triples method
The python slice syntax is (ab)used for specifying triples.
A generator over matches is returned,
the returned tuples include only the parts not given
>>> import rdflib
>>> g = rdflib.Graph()
>>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS
<Graph identifier=... (<class 'rdflib.graph.Graph'>)>
>>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob
[(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))]
>>> list(g[:namespace.RDFS.label]) # all label triples
[(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))]
>>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object
[(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))]
Combined with SPARQL paths, more complex queries can be
written concisely:
Name of all Bobs friends:
g[bob : FOAF.knows/FOAF.name ]
Some label for Bob:
g[bob : DC.title|FOAF.name|RDFS.label]
All friends and friends of friends of Bob
g[bob : FOAF.knows * "+"]
etc.
.. versionadded:: 4.0
"""
if isinstance(item, slice):
s, p, o = item.start, item.stop, item.step
if s is None and p is None and o is None:
return self.triples((s, p, o))
elif s is None and p is None:
return self.subject_predicates(o)
elif s is None and o is None:
return self.subject_objects(p)
elif p is None and o is None:
return self.predicate_objects(s)
elif s is None:
return self.subjects(p, o)
elif p is None:
return self.predicates(s, o)
elif o is None:
return self.objects(s, p)
else:
# all given
return (s, p, o) in self
elif isinstance(item, (Path, Node)):
return self.predicate_objects(item)
else:
raise TypeError(
"You can only index a graph by a single rdflib term or path, or a slice of rdflib terms."
)
def __len__(self) -> int:
"""Returns the number of triples in the graph
If context is specified then the number of triples in the context is
returned instead.
"""
# type error: Unexpected keyword argument "context" for "__len__" of "Store"
return self.__store.__len__(context=self) # type: ignore[call-arg]
def __iter__(self) -> Generator["_TripleType", None, None]:
"""Iterates over all triples in the store"""
return self.triples((None, None, None))
def __contains__(self, triple: _TripleSelectorType) -> bool:
"""Support for 'triple in graph' syntax"""
for triple in self.triples(triple):
return True
return False
def __hash__(self) -> int:
return hash(self.identifier)
def __cmp__(self, other) -> int:
if other is None:
return -1
elif isinstance(other, Graph):
return (self.identifier > other.identifier) - (
self.identifier < other.identifier
)
else:
# Note if None is considered equivalent to owl:Nothing
# Then perhaps a graph with length 0 should be considered
# equivalent to None (if compared to it)?
return 1
def __eq__(self, other) -> bool:
return isinstance(other, Graph) and self.identifier == other.identifier
def __lt__(self, other) -> bool:
return (other is None) or (
isinstance(other, Graph) and self.identifier < other.identifier
)
def __le__(self, other: Graph) -> bool:
return self < other or self == other
def __gt__(self, other) -> bool:
return (isinstance(other, Graph) and self.identifier > other.identifier) or (
other is not None
)
def __ge__(self, other: Graph) -> bool:
return self > other or self == other
def __iadd__(self: "_GraphT", other: Iterable["_TripleType"]) -> "_GraphT":
"""Add all triples in Graph other to Graph.
BNode IDs are not changed."""
self.addN((s, p, o, self) for s, p, o in other)
return self
def __isub__(self: "_GraphT", other: Iterable["_TripleType"]) -> "_GraphT":
"""Subtract all triples in Graph other from Graph.
BNode IDs are not changed."""
for triple in other:
self.remove(triple)
return self
def __add__(self, other: "Graph") -> "Graph":
"""Set-theoretic union
BNode IDs are not changed."""
try:
retval = type(self)()
except TypeError:
retval = Graph()
for prefix, uri in set(list(self.namespaces()) + list(other.namespaces())):
retval.bind(prefix, uri)
for x in self:
retval.add(x)
for y in other:
retval.add(y)
return retval
def __mul__(self, other: "Graph") -> "Graph":
"""Set-theoretic intersection.
BNode IDs are not changed."""
try:
retval = type(self)()
except TypeError:
retval = Graph()
for x in other:
if x in self:
retval.add(x)
return retval
def __sub__(self, other: "Graph") -> "Graph":
"""Set-theoretic difference.
BNode IDs are not changed."""
try:
retval = type(self)()
except TypeError:
retval = Graph()
for x in self:
if x not in other:
retval.add(x)
return retval
def __xor__(self, other: "Graph") -> "Graph":
"""Set-theoretic XOR.
BNode IDs are not changed."""
return (self - other) + (other - self)
__or__ = __add__
__and__ = __mul__
# Conv. methods
def set(
self: _GraphT, triple: Tuple[_SubjectType, _PredicateType, _ObjectType]
) -> _GraphT:
"""Convenience method to update the value of object
Remove any existing triples for subject and predicate before adding
(subject, predicate, object).
"""
(subject, predicate, object_) = triple
assert (
subject is not None
), "s can't be None in .set([s,p,o]), as it would remove (*, p, *)"
assert (
predicate is not None
), "p can't be None in .set([s,p,o]), as it would remove (s, *, *)"
self.remove((subject, predicate, None))
self.add((subject, predicate, object_))
return self
def subjects(
self,
predicate: Union[None, Path, "_PredicateType"] = None,
object: Optional["_ObjectType"] = None,
unique: bool = False,
) -> Generator["_SubjectType", None, None]:
"""A generator of (optionally unique) subjects with the given
predicate and object"""
if not unique:
for s, p, o in self.triples((None, predicate, object)):
yield s
else:
subs = set()
for s, p, o in self.triples((None, predicate, object)):
if s not in subs:
yield s
try:
subs.add(s)
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def predicates(
self,
subject: Optional["_SubjectType"] = None,
object: Optional["_ObjectType"] = None,
unique: bool = False,
) -> Generator["_PredicateType", None, None]:
"""A generator of (optionally unique) predicates with the given
subject and object"""
if not unique:
for s, p, o in self.triples((subject, None, object)):
yield p
else:
preds = set()
for s, p, o in self.triples((subject, None, object)):
if p not in preds:
yield p
try:
preds.add(p)
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def objects(
self,
subject: Optional["_SubjectType"] = None,
predicate: Union[None, Path, "_PredicateType"] = None,
unique: bool = False,
) -> Generator["_ObjectType", None, None]:
"""A generator of (optionally unique) objects with the given
subject and predicate"""
if not unique:
for s, p, o in self.triples((subject, predicate, None)):
yield o
else:
objs = set()
for s, p, o in self.triples((subject, predicate, None)):
if o not in objs:
yield o
try:
objs.add(o)
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def subject_predicates(
self, object: Optional["_ObjectType"] = None, unique: bool = False
) -> Generator[Tuple["_SubjectType", "_PredicateType"], None, None]:
"""A generator of (optionally unique) (subject, predicate) tuples
for the given object"""
if not unique:
for s, p, o in self.triples((None, None, object)):
yield s, p
else:
subj_preds = set()
for s, p, o in self.triples((None, None, object)):
if (s, p) not in subj_preds:
yield s, p
try:
subj_preds.add((s, p))
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def subject_objects(
self,
predicate: Union[None, Path, "_PredicateType"] = None,
unique: bool = False,
) -> Generator[Tuple["_SubjectType", "_ObjectType"], None, None]:
"""A generator of (optionally unique) (subject, object) tuples
for the given predicate"""
if not unique:
for s, p, o in self.triples((None, predicate, None)):
yield s, o
else:
subj_objs = set()
for s, p, o in self.triples((None, predicate, None)):
if (s, o) not in subj_objs:
yield s, o
try:
subj_objs.add((s, o))
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def predicate_objects(
self, subject: Optional["_SubjectType"] = None, unique: bool = False
) -> Generator[Tuple["_PredicateType", "_ObjectType"], None, None]:
"""A generator of (optionally unique) (predicate, object) tuples
for the given subject"""
if not unique:
for s, p, o in self.triples((subject, None, None)):
yield p, o
else:
pred_objs = set()
for s, p, o in self.triples((subject, None, None)):
if (p, o) not in pred_objs:
yield p, o
try:
pred_objs.add((p, o))
except MemoryError as e:
logger.error(
f"{e}. Consider not setting parameter 'unique' to True"
)
raise
def triples_choices(
self,
triple: Union[
Tuple[List["_SubjectType"], "_PredicateType", "_ObjectType"],
Tuple["_SubjectType", List["_PredicateType"], "_ObjectType"],
Tuple["_SubjectType", "_PredicateType", List["_ObjectType"]],
],
context: Optional["_ContextType"] = None,
) -> Generator[_TripleType, None, None]:
subject, predicate, object_ = triple
# type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
# type error note: unpacking discards type info
for (s, p, o), cg in self.store.triples_choices(
(subject, predicate, object_), context=self # type: ignore[arg-type]
):
yield s, p, o
@overload
def value(
self,
subject: None = ...,
predicate: None = ...,
object: Optional[_ObjectType] = ...,
default: Optional[Node] = ...,
any: bool = ...,
) -> None:
...
@overload
def value(
self,
subject: Optional[_SubjectType] = ...,
predicate: None = ...,
object: None = ...,
default: Optional[Node] = ...,
any: bool = ...,
) -> None:
...
@overload
def value(
self,
subject: None = ...,
predicate: Optional[_PredicateType] = ...,
object: None = ...,
default: Optional[Node] = ...,
any: bool = ...,
) -> None:
...
@overload
def value(
self,
subject: Optional[_SubjectType] = ...,
predicate: Optional[_PredicateType] = ...,
object: Optional[_ObjectType] = ...,
default: Optional[Node] = ...,
any: bool = ...,
) -> Optional[Node]:
...
def value(
self,
subject: Optional[_SubjectType] = None,