1
- from typing import Optional , Union , Type , cast , overload , Generator , Tuple
1
+ from typing import (
2
+ IO ,
3
+ Any ,
4
+ Iterable ,
5
+ Optional ,
6
+ Union ,
7
+ Type ,
8
+ cast ,
9
+ overload ,
10
+ Generator ,
11
+ Tuple ,
12
+ )
2
13
import logging
3
14
from warnings import warn
4
15
import random
21
32
import tempfile
22
33
import pathlib
23
34
24
- from io import BytesIO , BufferedIOBase
35
+ from io import BytesIO
25
36
from urllib .parse import urlparse
26
37
27
38
assert Literal # avoid warning
@@ -313,15 +324,19 @@ class Graph(Node):
313
324
"""
314
325
315
326
def __init__ (
316
- self , store = "default" , identifier = None , namespace_manager = None , base = None
327
+ self ,
328
+ store : Union [Store , str ] = "default" ,
329
+ identifier : Optional [Union [Node , str ]] = None ,
330
+ namespace_manager : Optional [NamespaceManager ] = None ,
331
+ base : Optional [str ] = None ,
317
332
):
318
333
super (Graph , self ).__init__ ()
319
334
self .base = base
320
- self .__identifier = identifier or BNode ()
321
-
335
+ self .__identifier : Node
336
+ self . __identifier = identifier or BNode () # type: ignore[assignment]
322
337
if not isinstance (self .__identifier , Node ):
323
- self .__identifier = URIRef (self .__identifier )
324
-
338
+ self .__identifier = URIRef (self .__identifier ) # type: ignore[unreachable]
339
+ self . __store : Store
325
340
if not isinstance (store , Store ):
326
341
# TODO: error handling
327
342
self .__store = store = plugin .get (store , Store )()
@@ -404,7 +419,7 @@ def close(self, commit_pending_transaction=False):
404
419
"""
405
420
return self .__store .close (commit_pending_transaction = commit_pending_transaction )
406
421
407
- def add (self , triple ):
422
+ def add (self , triple : Tuple [ Node , Node , Node ] ):
408
423
"""Add a triple with self as context"""
409
424
s , p , o = triple
410
425
assert isinstance (s , Node ), "Subject %s must be an rdflib term" % (s ,)
@@ -413,7 +428,7 @@ def add(self, triple):
413
428
self .__store .add ((s , p , o ), self , quoted = False )
414
429
return self
415
430
416
- def addN (self , quads ):
431
+ def addN (self , quads : Iterable [ Tuple [ Node , Node , Node , Any ]] ):
417
432
"""Add a sequence of triple with context"""
418
433
419
434
self .__store .addN (
@@ -434,7 +449,9 @@ def remove(self, triple):
434
449
self .__store .remove (triple , context = self )
435
450
return self
436
451
437
- def triples (self , triple ):
452
+ def triples (
453
+ self , triple : Tuple [Optional [Node ], Union [None , Path , Node ], Optional [Node ]]
454
+ ):
438
455
"""Generator over the triple store
439
456
440
457
Returns triples that match the given triple pattern. If triple pattern
@@ -652,17 +669,17 @@ def set(self, triple):
652
669
self .add ((subject , predicate , object_ ))
653
670
return self
654
671
655
- def subjects (self , predicate = None , object = None ):
672
+ def subjects (self , predicate = None , object = None ) -> Iterable [ Node ] :
656
673
"""A generator of subjects with the given predicate and object"""
657
674
for s , p , o in self .triples ((None , predicate , object )):
658
675
yield s
659
676
660
- def predicates (self , subject = None , object = None ):
677
+ def predicates (self , subject = None , object = None ) -> Iterable [ Node ] :
661
678
"""A generator of predicates with the given subject and object"""
662
679
for s , p , o in self .triples ((subject , None , object )):
663
680
yield p
664
681
665
- def objects (self , subject = None , predicate = None ):
682
+ def objects (self , subject = None , predicate = None ) -> Iterable [ Node ] :
666
683
"""A generator of objects with the given subject and predicate"""
667
684
for s , p , o in self .triples ((subject , predicate , None )):
668
685
yield o
@@ -1011,53 +1028,45 @@ def absolutize(self, uri, defrag=1):
1011
1028
# no destination and non-None positional encoding
1012
1029
@overload
1013
1030
def serialize (
1014
- self , destination : None , format : str , base : Optional [str ], encoding : str , ** args
1031
+ self ,
1032
+ destination : None ,
1033
+ format : str ,
1034
+ base : Optional [str ],
1035
+ encoding : str ,
1036
+ ** args ,
1015
1037
) -> bytes :
1016
1038
...
1017
1039
1018
1040
# no destination and non-None keyword encoding
1019
1041
@overload
1020
1042
def serialize (
1021
1043
self ,
1022
- * ,
1023
1044
destination : None = ...,
1024
1045
format : str = ...,
1025
1046
base : Optional [str ] = ...,
1047
+ * ,
1026
1048
encoding : str ,
1027
1049
** args ,
1028
1050
) -> bytes :
1029
1051
...
1030
1052
1031
- # no destination and None positional encoding
1053
+ # no destination and None encoding
1032
1054
@overload
1033
1055
def serialize (
1034
1056
self ,
1035
- destination : None ,
1036
- format : str ,
1037
- base : Optional [str ],
1038
- encoding : None ,
1039
- ** args ,
1040
- ) -> str :
1041
- ...
1042
-
1043
- # no destination and None keyword encoding
1044
- @overload
1045
- def serialize (
1046
- self ,
1047
- * ,
1048
1057
destination : None = ...,
1049
1058
format : str = ...,
1050
1059
base : Optional [str ] = ...,
1051
- encoding : None = None ,
1060
+ encoding : None = ... ,
1052
1061
** args ,
1053
1062
) -> str :
1054
1063
...
1055
1064
1056
- # non-none destination
1065
+ # non-None destination
1057
1066
@overload
1058
1067
def serialize (
1059
1068
self ,
1060
- destination : Union [str , BufferedIOBase , pathlib .PurePath ],
1069
+ destination : Union [str , pathlib .PurePath , IO [ bytes ] ],
1061
1070
format : str = ...,
1062
1071
base : Optional [str ] = ...,
1063
1072
encoding : Optional [str ] = ...,
@@ -1069,21 +1078,21 @@ def serialize(
1069
1078
@overload
1070
1079
def serialize (
1071
1080
self ,
1072
- destination : Union [str , BufferedIOBase , pathlib .PurePath , None ] = None ,
1073
- format : str = "turtle" ,
1074
- base : Optional [str ] = None ,
1075
- encoding : Optional [str ] = None ,
1081
+ destination : Optional [ Union [str , pathlib .PurePath , IO [ bytes ]]] = ... ,
1082
+ format : str = ... ,
1083
+ base : Optional [str ] = ... ,
1084
+ encoding : Optional [str ] = ... ,
1076
1085
** args ,
1077
1086
) -> Union [bytes , str , "Graph" ]:
1078
1087
...
1079
1088
1080
1089
def serialize (
1081
1090
self ,
1082
- destination : Union [str , BufferedIOBase , pathlib .PurePath , None ] = None ,
1091
+ destination : Optional [ Union [str , pathlib .PurePath , IO [ bytes ]] ] = None ,
1083
1092
format : str = "turtle" ,
1084
1093
base : Optional [str ] = None ,
1085
1094
encoding : Optional [str ] = None ,
1086
- ** args ,
1095
+ ** args : Any ,
1087
1096
) -> Union [bytes , str , "Graph" ]:
1088
1097
"""Serialize the Graph to destination
1089
1098
@@ -1104,7 +1113,7 @@ def serialize(
1104
1113
base = self .base
1105
1114
1106
1115
serializer = plugin .get (format , Serializer )(self )
1107
- stream : BufferedIOBase
1116
+ stream : IO [ bytes ]
1108
1117
if destination is None :
1109
1118
stream = BytesIO ()
1110
1119
if encoding is None :
@@ -1114,7 +1123,7 @@ def serialize(
1114
1123
serializer .serialize (stream , base = base , encoding = encoding , ** args )
1115
1124
return stream .getvalue ()
1116
1125
if hasattr (destination , "write" ):
1117
- stream = cast (BufferedIOBase , destination )
1126
+ stream = cast (IO [ bytes ] , destination )
1118
1127
serializer .serialize (stream , base = base , encoding = encoding , ** args )
1119
1128
else :
1120
1129
if isinstance (destination , pathlib .PurePath ):
@@ -1149,10 +1158,10 @@ def parse(
1149
1158
self ,
1150
1159
source = None ,
1151
1160
publicID = None ,
1152
- format = None ,
1161
+ format : Optional [ str ] = None ,
1153
1162
location = None ,
1154
1163
file = None ,
1155
- data = None ,
1164
+ data : Optional [ Union [ str , bytes , bytearray ]] = None ,
1156
1165
** args ,
1157
1166
):
1158
1167
"""
@@ -1537,7 +1546,12 @@ class ConjunctiveGraph(Graph):
1537
1546
All queries are carried out against the union of all graphs.
1538
1547
"""
1539
1548
1540
- def __init__ (self , store = "default" , identifier = None , default_graph_base = None ):
1549
+ def __init__ (
1550
+ self ,
1551
+ store : Union [Store , str ] = "default" ,
1552
+ identifier : Optional [Union [Node , str ]] = None ,
1553
+ default_graph_base : Optional [str ] = None ,
1554
+ ):
1541
1555
super (ConjunctiveGraph , self ).__init__ (store , identifier = identifier )
1542
1556
assert self .store .context_aware , (
1543
1557
"ConjunctiveGraph must be backed by" " a context aware store."
@@ -1555,7 +1569,31 @@ def __str__(self):
1555
1569
)
1556
1570
return pattern % self .store .__class__ .__name__
1557
1571
1558
- def _spoc (self , triple_or_quad , default = False ):
1572
+ @overload
1573
+ def _spoc (
1574
+ self ,
1575
+ triple_or_quad : Union [
1576
+ Tuple [Node , Node , Node , Optional [Any ]], Tuple [Node , Node , Node ]
1577
+ ],
1578
+ default : bool = False ,
1579
+ ) -> Tuple [Node , Node , Node , Optional [Graph ]]:
1580
+ ...
1581
+
1582
+ @overload
1583
+ def _spoc (
1584
+ self ,
1585
+ triple_or_quad : None ,
1586
+ default : bool = False ,
1587
+ ) -> Tuple [None , None , None , Optional [Graph ]]:
1588
+ ...
1589
+
1590
+ def _spoc (
1591
+ self ,
1592
+ triple_or_quad : Optional [
1593
+ Union [Tuple [Node , Node , Node , Optional [Any ]], Tuple [Node , Node , Node ]]
1594
+ ],
1595
+ default : bool = False ,
1596
+ ) -> Tuple [Optional [Node ], Optional [Node ], Optional [Node ], Optional [Graph ]]:
1559
1597
"""
1560
1598
helper method for having methods that support
1561
1599
either triples or quads
@@ -1564,9 +1602,9 @@ def _spoc(self, triple_or_quad, default=False):
1564
1602
return (None , None , None , self .default_context if default else None )
1565
1603
if len (triple_or_quad ) == 3 :
1566
1604
c = self .default_context if default else None
1567
- (s , p , o ) = triple_or_quad
1605
+ (s , p , o ) = triple_or_quad # type: ignore[misc]
1568
1606
elif len (triple_or_quad ) == 4 :
1569
- (s , p , o , c ) = triple_or_quad
1607
+ (s , p , o , c ) = triple_or_quad # type: ignore[misc]
1570
1608
c = self ._graph (c )
1571
1609
return s , p , o , c
1572
1610
@@ -1577,7 +1615,7 @@ def __contains__(self, triple_or_quad):
1577
1615
return True
1578
1616
return False
1579
1617
1580
- def add (self , triple_or_quad ):
1618
+ def add (self , triple_or_quad : Union [ Tuple [ Node , Node , Node , Optional [ Any ]], Tuple [ Node , Node , Node ]]) -> "ConjunctiveGraph" : # type: ignore[override]
1581
1619
"""
1582
1620
Add a triple or quad to the store.
1583
1621
@@ -1591,15 +1629,23 @@ def add(self, triple_or_quad):
1591
1629
self .store .add ((s , p , o ), context = c , quoted = False )
1592
1630
return self
1593
1631
1594
- def _graph (self , c ):
1632
+ @overload
1633
+ def _graph (self , c : Union [Graph , Node , str ]) -> Graph :
1634
+ ...
1635
+
1636
+ @overload
1637
+ def _graph (self , c : None ) -> None :
1638
+ ...
1639
+
1640
+ def _graph (self , c : Optional [Union [Graph , Node , str ]]) -> Optional [Graph ]:
1595
1641
if c is None :
1596
1642
return None
1597
1643
if not isinstance (c , Graph ):
1598
1644
return self .get_context (c )
1599
1645
else :
1600
1646
return c
1601
1647
1602
- def addN (self , quads ):
1648
+ def addN (self , quads : Iterable [ Tuple [ Node , Node , Node , Any ]] ):
1603
1649
"""Add a sequence of triples with context"""
1604
1650
1605
1651
self .store .addN (
@@ -1689,13 +1735,19 @@ def contexts(self, triple=None):
1689
1735
else :
1690
1736
yield self .get_context (context )
1691
1737
1692
- def get_context (self , identifier , quoted = False , base = None ):
1738
+ def get_context (
1739
+ self ,
1740
+ identifier : Optional [Union [Node , str ]],
1741
+ quoted : bool = False ,
1742
+ base : Optional [str ] = None ,
1743
+ ) -> Graph :
1693
1744
"""Return a context graph for the given identifier
1694
1745
1695
1746
identifier must be a URIRef or BNode.
1696
1747
"""
1748
+ # TODO: FIXME - why is ConjunctiveGraph passed as namespace_manager?
1697
1749
return Graph (
1698
- store = self .store , identifier = identifier , namespace_manager = self , base = base
1750
+ store = self .store , identifier = identifier , namespace_manager = self , base = base # type: ignore[arg-type]
1699
1751
)
1700
1752
1701
1753
def remove_context (self , context ):
@@ -1747,6 +1799,7 @@ def parse(
1747
1799
context = Graph (store = self .store , identifier = g_id )
1748
1800
context .remove ((None , None , None )) # hmm ?
1749
1801
context .parse (source , publicID = publicID , format = format , ** args )
1802
+ # TODO: FIXME: This should not return context, but self.
1750
1803
return context
1751
1804
1752
1805
def __reduce__ (self ):
@@ -1977,7 +2030,7 @@ class QuotedGraph(Graph):
1977
2030
def __init__ (self , store , identifier ):
1978
2031
super (QuotedGraph , self ).__init__ (store , identifier )
1979
2032
1980
- def add (self , triple ):
2033
+ def add (self , triple : Tuple [ Node , Node , Node ] ):
1981
2034
"""Add a triple with self as context"""
1982
2035
s , p , o = triple
1983
2036
assert isinstance (s , Node ), "Subject %s must be an rdflib term" % (s ,)
@@ -1987,7 +2040,7 @@ def add(self, triple):
1987
2040
self .store .add ((s , p , o ), self , quoted = True )
1988
2041
return self
1989
2042
1990
- def addN (self , quads ):
2043
+ def addN (self , quads : Tuple [ Node , Node , Node , Any ]) -> "QuotedGraph" : # type: ignore[override]
1991
2044
"""Add a sequence of triple with context"""
1992
2045
1993
2046
self .store .addN (
@@ -2261,7 +2314,7 @@ class BatchAddGraph(object):
2261
2314
2262
2315
"""
2263
2316
2264
- def __init__ (self , graph , batch_size = 1000 , batch_addn = False ):
2317
+ def __init__ (self , graph : Graph , batch_size : int = 1000 , batch_addn : bool = False ):
2265
2318
if not batch_size or batch_size < 2 :
2266
2319
raise ValueError ("batch_size must be a positive number" )
2267
2320
self .graph = graph
@@ -2278,7 +2331,10 @@ def reset(self):
2278
2331
self .count = 0
2279
2332
return self
2280
2333
2281
- def add (self , triple_or_quad ):
2334
+ def add (
2335
+ self ,
2336
+ triple_or_quad : Union [Tuple [Node , Node , Node ], Tuple [Node , Node , Node , Any ]],
2337
+ ) -> "BatchAddGraph" :
2282
2338
"""
2283
2339
Add a triple to the buffer
2284
2340
@@ -2294,7 +2350,7 @@ def add(self, triple_or_quad):
2294
2350
self .batch .append (triple_or_quad )
2295
2351
return self
2296
2352
2297
- def addN (self , quads ):
2353
+ def addN (self , quads : Iterable [ Tuple [ Node , Node , Node , Any ]] ):
2298
2354
if self .__batch_addn :
2299
2355
for q in quads :
2300
2356
self .add (q )
0 commit comments