Skip to content

Commit 0679f89

Browse files
committed
[DO NOT REVIEW] Add a bunch of typing
This is a branch I'm maintaing with a bunch of typing, I'm planning to integrate it with master in parts, anyone is welcome to have a look but most of what is happening here is subject to change.
1 parent 3a41821 commit 0679f89

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+1621
-707
lines changed

docs/conf.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,9 @@ def find_version(filename):
304304
("py:class", "_TripleType"),
305305
("py:class", "_TripleOrTriplePathType"),
306306
("py:class", "TextIO"),
307+
("py:class", "HTTPResponse"),
308+
("py:class", "HTTPMessage"),
309+
("py:class", "EntryPoint"),
307310
]
308311
)
309312

rdflib/_type_checking.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@
2727
from typing_extensions import Literal as PyLiteral
2828

2929
_NamespaceSetString = PyLiteral["core", "rdflib", "none"]
30+
_MulPathMod = PyLiteral["*", "+", "?"] # noqa: F722

rdflib/_typing.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# import sys
2+
# from typing import TYPE_CHECKING, Optional, Tuple, TypeVar
3+
4+
# if sys.version_info >= (3, 10):
5+
# from typing import TypeAlias
6+
# else:
7+
# from typing_extensions import TypeAlias
8+
9+
# if TYPE_CHECKING:
10+
# from rdflib.graph import Graph
11+
# from rdflib.term import IdentifiedNode, Identifier
12+
13+
# _SubjectType: TypeAlias = "IdentifiedNode"
14+
# _PredicateType: TypeAlias = "IdentifiedNode"
15+
# _ObjectType: TypeAlias = "Identifier"
16+
17+
# _TripleType = Tuple["_SubjectType", "_PredicateType", "_ObjectType"]
18+
# _QuadType = Tuple["_SubjectType", "_PredicateType", "_ObjectType", "Graph"]
19+
# _TriplePatternType = Tuple[
20+
# Optional["_SubjectType"], Optional["_PredicateType"], Optional["_ObjectType"]
21+
# ]
22+
23+
# _GraphT = TypeVar("_GraphT", bound="Graph")

rdflib/collection.py

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional
4+
15
from rdflib.namespace import RDF
2-
from rdflib.term import BNode, Literal
6+
from rdflib.term import BNode, Node
7+
8+
if TYPE_CHECKING:
9+
from rdflib import Graph
310

411
__all__ = ["Collection"]
512

@@ -9,6 +16,7 @@ class Collection(object):
916
See "Emulating container types":
1017
https://docs.python.org/reference/datamodel.html#emulating-container-types
1118
19+
>>> from rdflib.term import Literal
1220
>>> from rdflib.graph import Graph
1321
>>> from pprint import pprint
1422
>>> listname = BNode()
@@ -43,13 +51,14 @@ class Collection(object):
4351
True
4452
"""
4553

46-
def __init__(self, graph, uri, seq=[]):
54+
def __init__(self, graph: Graph, uri: Node, seq: List[Node] = []):
4755
self.graph = graph
4856
self.uri = uri or BNode()
4957
self += seq
5058

51-
def n3(self):
59+
def n3(self) -> str:
5260
"""
61+
>>> from rdflib.term import Literal
5362
>>> from rdflib.graph import Graph
5463
>>> listname = BNode()
5564
>>> g = Graph('Memory')
@@ -73,13 +82,14 @@ def n3(self):
7382
"2"^^<http://www.w3.org/2001/XMLSchema#integer>
7483
"3"^^<http://www.w3.org/2001/XMLSchema#integer> )
7584
"""
76-
return "( %s )" % (" ".join([i.n3() for i in self]))
85+
# type error: "Node" has no attribute "n3"
86+
return "( %s )" % (" ".join([i.n3() for i in self])) # type: ignore[attr-defined]
7787

78-
def _get_container(self, index):
88+
def _get_container(self, index: int) -> Optional[Node]:
7989
"""Gets the first, rest holding node at index."""
8090
assert isinstance(index, int)
8191
graph = self.graph
82-
container = self.uri
92+
container: Optional[Node] = self.uri
8393
i = 0
8494
while i < index:
8595
i += 1
@@ -88,11 +98,11 @@ def _get_container(self, index):
8898
break
8999
return container
90100

91-
def __len__(self):
101+
def __len__(self) -> int:
92102
"""length of items in collection."""
93103
return len(list(self.graph.items(self.uri)))
94104

95-
def index(self, item):
105+
def index(self, item: Node) -> int:
96106
"""
97107
Returns the 0-based numerical index of the item in the list
98108
"""
@@ -112,7 +122,7 @@ def index(self, item):
112122
assert len(newlink) == 1, "Malformed RDF Collection: %s" % self.uri
113123
listname = newlink[0]
114124

115-
def __getitem__(self, key):
125+
def __getitem__(self, key: int) -> Node:
116126
"""TODO"""
117127
c = self._get_container(key)
118128
if c:
@@ -124,15 +134,15 @@ def __getitem__(self, key):
124134
else:
125135
raise IndexError(key)
126136

127-
def __setitem__(self, key, value):
137+
def __setitem__(self, key: int, value: Node) -> None:
128138
"""TODO"""
129139
c = self._get_container(key)
130140
if c:
131141
self.graph.set((c, RDF.first, value))
132142
else:
133143
raise IndexError(key)
134144

135-
def __delitem__(self, key):
145+
def __delitem__(self, key: int) -> None:
136146
"""
137147
>>> from rdflib.namespace import RDF, RDFS
138148
>>> from rdflib import Graph
@@ -184,7 +194,8 @@ def __delitem__(self, key):
184194
elif key == len(self) - 1:
185195
# the tail
186196
priorlink = self._get_container(key - 1)
187-
self.graph.set((priorlink, RDF.rest, RDF.nil))
197+
# type error: Argument 1 to "set" of "Graph" has incompatible type "Tuple[Optional[Node], URIRef, URIRef]"; expected "Tuple[Node, Node, Any]"
198+
self.graph.set((priorlink, RDF.rest, RDF.nil)) # type: ignore[arg-type]
188199
graph.remove((current, None, None))
189200
else:
190201
next = self._get_container(key + 1)
@@ -193,11 +204,11 @@ def __delitem__(self, key):
193204
graph.remove((current, None, None))
194205
graph.set((prior, RDF.rest, next))
195206

196-
def __iter__(self):
207+
def __iter__(self) -> Iterator[Node]:
197208
"""Iterator over items in Collections"""
198209
return self.graph.items(self.uri)
199210

200-
def _end(self):
211+
def _end(self) -> Node:
201212
# find end of list
202213
container = self.uri
203214
while True:
@@ -207,8 +218,9 @@ def _end(self):
207218
else:
208219
container = rest
209220

210-
def append(self, item):
221+
def append(self, item: Node) -> Collection:
211222
"""
223+
>>> from rdflib.term import Literal
212224
>>> from rdflib.graph import Graph
213225
>>> listname = BNode()
214226
>>> g = Graph()
@@ -231,7 +243,7 @@ def append(self, item):
231243
self.graph.add((end, RDF.rest, RDF.nil))
232244
return self
233245

234-
def __iadd__(self, other):
246+
def __iadd__(self, other: Iterable[Node]) -> Collection:
235247

236248
end = self._end()
237249
self.graph.remove((end, RDF.rest, None))
@@ -247,8 +259,8 @@ def __iadd__(self, other):
247259
self.graph.add((end, RDF.rest, RDF.nil))
248260
return self
249261

250-
def clear(self):
251-
container = self.uri
262+
def clear(self) -> Collection:
263+
container: Optional[Node] = self.uri
252264
graph = self.graph
253265
while container:
254266
rest = graph.value(container, RDF.rest)

rdflib/compat.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
and different versions of support libraries.
44
"""
55

6+
from __future__ import annotations
7+
68
import codecs
79
import re
810
import warnings
@@ -101,6 +103,6 @@ def decodeUnicodeEscape(escaped: str) -> str:
101103

102104
# Migration to abc in Python 3.8
103105
try:
104-
from collections.abc import Mapping, MutableMapping
106+
from collections.abc import Mapping, MutableMapping # noqa: F401
105107
except:
106-
from collections import Mapping, MutableMapping
108+
pass

rdflib/exceptions.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,36 @@
55
__all__ = [
66
"Error",
77
"ParserError",
8+
"UniquenessError",
89
]
910

1011

12+
from typing import Any, Optional
13+
14+
1115
class Error(Exception):
1216
"""Base class for rdflib exceptions."""
1317

14-
def __init__(self, msg=None):
18+
def __init__(self, msg: Optional[str] = None):
1519
Exception.__init__(self, msg)
1620
self.msg = msg
1721

1822

1923
class ParserError(Error):
2024
"""RDF Parser error."""
2125

22-
def __init__(self, msg):
26+
def __init__(self, msg: str):
2327
Error.__init__(self, msg)
24-
self.msg = msg
28+
self.msg: str = msg
2529

26-
def __str__(self):
30+
def __str__(self) -> str:
2731
return self.msg
2832

2933

3034
class UniquenessError(Error):
3135
"""A uniqueness assumption was made in the context, and that is not true"""
3236

33-
def __init__(self, values):
37+
def __init__(self, values: Any):
3438
Error.__init__(
3539
self,
3640
"\

rdflib/extras/external_graph_libs.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
"""
1414

1515
import logging
16+
from typing import Any, Dict, List
17+
18+
from rdflib.graph import Graph
1619

1720
logger = logging.getLogger(__name__)
1821

@@ -22,9 +25,9 @@ def _identity(x):
2225

2326

2427
def _rdflib_to_networkx_graph(
25-
graph,
28+
graph: Graph,
2629
nxgraph,
27-
calc_weights,
30+
calc_weights: bool,
2831
edge_attrs,
2932
transform_s=_identity,
3033
transform_o=_identity,
@@ -70,7 +73,7 @@ def _rdflib_to_networkx_graph(
7073

7174

7275
def rdflib_to_networkx_multidigraph(
73-
graph, edge_attrs=lambda s, p, o: {"key": p}, **kwds
76+
graph: Graph, edge_attrs=lambda s, p, o: {"key": p}, **kwds
7477
):
7578
"""Converts the given graph into a networkx.MultiDiGraph.
7679
@@ -124,8 +127,8 @@ def rdflib_to_networkx_multidigraph(
124127

125128

126129
def rdflib_to_networkx_digraph(
127-
graph,
128-
calc_weights=True,
130+
graph: Graph,
131+
calc_weights: bool = True,
129132
edge_attrs=lambda s, p, o: {"triples": [(s, p, o)]},
130133
**kwds,
131134
):
@@ -187,8 +190,8 @@ def rdflib_to_networkx_digraph(
187190

188191

189192
def rdflib_to_networkx_graph(
190-
graph,
191-
calc_weights=True,
193+
graph: Graph,
194+
calc_weights: bool = True,
192195
edge_attrs=lambda s, p, o: {"triples": [(s, p, o)]},
193196
**kwds,
194197
):
@@ -250,9 +253,9 @@ def rdflib_to_networkx_graph(
250253

251254

252255
def rdflib_to_graphtool(
253-
graph,
254-
v_prop_names=[str("term")],
255-
e_prop_names=[str("term")],
256+
graph: Graph,
257+
v_prop_names: List[str] = [str("term")],
258+
e_prop_names: List[str] = [str("term")],
256259
transform_s=lambda s, p, o: {str("term"): s},
257260
transform_p=lambda s, p, o: {str("term"): p},
258261
transform_o=lambda s, p, o: {str("term"): o},
@@ -313,7 +316,8 @@ def rdflib_to_graphtool(
313316
True
314317
315318
"""
316-
import graph_tool as gt
319+
# pytype error: Can't find module 'graph_tool'.
320+
import graph_tool as gt # pytype: disable=import-error
317321

318322
g = gt.Graph()
319323

@@ -323,7 +327,7 @@ def rdflib_to_graphtool(
323327
eprops = [(epn, g.new_edge_property("object")) for epn in e_prop_names]
324328
for epn, eprop in eprops:
325329
g.edge_properties[epn] = eprop
326-
node_to_vertex = {}
330+
node_to_vertex: Dict[Any, Any] = {}
327331
for s, p, o in graph:
328332
sv = node_to_vertex.get(s)
329333
if sv is None:

rdflib/extras/infixowl.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,10 @@
110110
import itertools
111111
import logging
112112

113-
from rdflib import OWL, RDF, RDFS, XSD, BNode, Literal, Namespace, URIRef, Variable
114113
from rdflib.collection import Collection
115114
from rdflib.graph import Graph
116-
from rdflib.namespace import NamespaceManager
117-
from rdflib.term import Identifier
115+
from rdflib.namespace import OWL, RDF, RDFS, XSD, Namespace, NamespaceManager
116+
from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
118117
from rdflib.util import first
119118

120119
logger = logging.getLogger(__name__)

rdflib/namespace/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import json
21
import logging
3-
import sys
42
import warnings
53
from functools import lru_cache
64
from pathlib import Path

0 commit comments

Comments
 (0)