Skip to content

Commit f53b070

Browse files
committed
iwana-20220126T2212-typing: checkpoint 20230908T003652 - SQ
[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 0450ea2 commit f53b070

File tree

26 files changed

+344
-161
lines changed

26 files changed

+344
-161
lines changed

docs/conf.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,6 @@ def find_version(filename):
285285
("py:class", "pyparsing.core.ParserElement"),
286286
]
287287

288-
289288
def autodoc_skip_member_handler(
290289
app: sphinx.application.Sphinx,
291290
what: str,

examples/resource_example.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
bill.add(RDF.type, FOAF.Agent)
2626
bill.set(RDFS.label, Literal("Bill"))
2727

28-
bill.add(FOAF.knows, bob)
28+
# type error: Argument 2 to "add" of "Resource" has incompatible type "Resource"; expected "Node" [arg-type]
29+
bill.add(FOAF.knows, bob) # type: ignore[arg-type]
2930

3031
# Resources returned when querying are 'auto-boxed' as resources:
3132
print(f"Bill knows: {bill.value(FOAF.knows).value(FOAF.name)}")

pyproject.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,11 @@ no_implicit_optional = false
255255
implicit_reexport = false
256256

257257

258+
[[tool.mypy.overrides]]
259+
module = "rdflib.*"
260+
check_untyped_defs = true
261+
262+
258263
[tool.coverage.run]
259264
branch = true
260265
source = ["rdflib"]

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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def append(self, item: Node) -> Collection:
242242
self.graph.add((end, RDF.rest, RDF.nil))
243243
return self
244244

245-
def __iadd__(self, other: Iterable[Node]):
245+
def __iadd__(self, other: Iterable[Node]) -> Collection:
246246
end = self._end()
247247
self.graph.remove((end, RDF.rest, None))
248248

@@ -257,7 +257,7 @@ def __iadd__(self, other: Iterable[Node]):
257257
self.graph.add((end, RDF.rest, RDF.nil))
258258
return self
259259

260-
def clear(self):
260+
def clear(self) -> Collection:
261261
container: Optional[Node] = self.uri
262262
graph = self.graph
263263
while container:

rdflib/compat.py

Lines changed: 4 additions & 1 deletion
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
@@ -20,7 +22,8 @@ def ascii(stream):
2022

2123

2224
def bopen(*args, **kwargs):
23-
return open(*args, mode="rb", **kwargs)
25+
# type error: No overload variant of "open" matches argument types "Tuple[Any, ...]", "str", "Dict[str, Any]"
26+
return open(*args, mode="rb", **kwargs) # type: ignore[call-overload]
2427

2528

2629
long_type = int

rdflib/events.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@
2525

2626
from __future__ import annotations
2727

28-
from typing import Any, Dict, Optional
28+
from typing import TYPE_CHECKING, Any, Dict, Optional
29+
30+
if TYPE_CHECKING:
31+
import typing_extensions as te
2932

3033
__all__ = ["Event", "Dispatcher"]
3134

@@ -59,7 +62,7 @@ class Dispatcher:
5962

6063
_dispatch_map: Optional[Dict[Any, Any]] = None
6164

62-
def set_map(self, amap: Dict[Any, Any]):
65+
def set_map(self, amap: Dict[Any, Any]) -> te.Self:
6366
self._dispatch_map = amap
6467
return self
6568

@@ -72,12 +75,14 @@ def subscribe(self, event_type, handler):
7275
"""
7376
if self._dispatch_map is None:
7477
self.set_map({})
75-
lst = self._dispatch_map.get(event_type, None)
78+
# type error: error: Item "None" of "Optional[Dict[Any, Any]]" has no attribute "get"
79+
lst = self._dispatch_map.get(event_type, None) # type: ignore[union-attr]
7680
if lst is None:
7781
lst = [handler]
7882
else:
7983
lst.append(handler)
80-
self._dispatch_map[event_type] = lst
84+
# type error: Unsupported target for indexed assignment ("Optional[Dict[Any, Any]]")
85+
self._dispatch_map[event_type] = lst # type: ignore[index]
8186
return self
8287

8388
def dispatch(self, event):

rdflib/plugins/parsers/jsonld.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,13 @@ def to_rdf(
122122
data: Any,
123123
dataset: Graph,
124124
base: Optional[str] = None,
125-
context_data: Optional[bool] = None,
125+
context_data: Optional[
126+
Union[
127+
List[Union[Dict[str, Any], str, None]],
128+
Dict[str, Any],
129+
str,
130+
]
131+
] = None,
126132
version: Optional[float] = None,
127133
generalized_rdf: bool = False,
128134
allow_lists_of_lists: Optional[bool] = None,

rdflib/plugins/parsers/rdfxml.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,14 @@ class BagID(URIRef):
8787
__slots__ = ["li"]
8888

8989
def __init__(self, val):
90-
super(URIRef, self).__init__(val)
90+
# type error: Too many arguments for "__init__" of "object"
91+
super(URIRef, self).__init__(val) # type: ignore[call-arg]
9192
self.li = 0
9293

9394
def next_li(self):
9495
self.li += 1
95-
return RDFNS["_%s" % self.li]
96+
# type error: Type expected within [...]
97+
return RDFNS["_%s" % self.li] # type: ignore[misc]
9698

9799

98100
class ElementHandler:

rdflib/plugins/serializers/jsonld.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,20 @@
3737
from __future__ import annotations
3838

3939
import warnings
40-
from typing import IO, Optional
40+
from typing import IO, TYPE_CHECKING, Any, Dict, List, Optional
4141

4242
from rdflib.graph import Graph
4343
from rdflib.namespace import RDF, XSD
4444
from rdflib.serializer import Serializer
45-
from rdflib.term import BNode, Literal, URIRef
45+
from rdflib.term import BNode, IdentifiedNode, Identifier, Literal, URIRef
4646

4747
from ..shared.jsonld.context import UNDEF, Context
4848
from ..shared.jsonld.keys import CONTEXT, GRAPH, ID, LANG, LIST, SET, VOCAB
4949
from ..shared.jsonld.util import json
5050

51+
if TYPE_CHECKING:
52+
pass
53+
5154
__all__ = ["JsonLDSerializer", "from_rdf"]
5255

5356

@@ -140,12 +143,12 @@ def from_rdf(
140143

141144

142145
class Converter:
143-
def __init__(self, context, use_native_types, use_rdf_type):
146+
def __init__(self, context: Context, use_native_types: bool, use_rdf_type: bool):
144147
self.context = context
145148
self.use_native_types = context.active or use_native_types
146149
self.use_rdf_type = use_rdf_type
147150

148-
def convert(self, graph):
151+
def convert(self, graph: Graph):
149152
# TODO: bug in rdflib dataset parsing (nquads et al):
150153
# plain triples end up in separate unnamed graphs (rdflib issue #436)
151154
if graph.context_aware:
@@ -161,7 +164,7 @@ def convert(self, graph):
161164

162165
context = self.context
163166

164-
objs = []
167+
objs: List[Any] = []
165168
for g in graphs:
166169
obj = {}
167170
graphname = None
@@ -194,8 +197,8 @@ def convert(self, graph):
194197

195198
return objs
196199

197-
def from_graph(self, graph):
198-
nodemap = {}
200+
def from_graph(self, graph: Graph):
201+
nodemap: Dict[Any, Any] = {}
199202

200203
for s in set(graph.subjects()):
201204
## only iri:s and unreferenced (rest will be promoted to top if needed)
@@ -206,12 +209,13 @@ def from_graph(self, graph):
206209

207210
return list(nodemap.values())
208211

209-
def process_subject(self, graph, s, nodemap):
212+
def process_subject(self, graph: Graph, s: IdentifiedNode, nodemap):
210213
if isinstance(s, URIRef):
211214
node_id = self.context.shrink_iri(s)
212215
elif isinstance(s, BNode):
213216
node_id = s.n3()
214217
else:
218+
# This does not seem right, this probably should be an error.
215219
node_id = None
216220

217221
# used_as_object = any(graph.subjects(None, s))
@@ -227,7 +231,15 @@ def process_subject(self, graph, s, nodemap):
227231

228232
return node
229233

230-
def add_to_node(self, graph, s, p, o, s_node, nodemap):
234+
def add_to_node(
235+
self,
236+
graph: Graph,
237+
s: IdentifiedNode,
238+
p: IdentifiedNode,
239+
o: Identifier,
240+
s_node: Dict[str, Any],
241+
nodemap,
242+
):
231243
context = self.context
232244

233245
if isinstance(o, Literal):
@@ -302,7 +314,7 @@ def add_to_node(self, graph, s, p, o, s_node, nodemap):
302314
value = node
303315
s_node[p_key] = value
304316

305-
def type_coerce(self, o, coerce_type):
317+
def type_coerce(self, o: IdentifiedNode, coerce_type: str):
306318
if coerce_type == ID:
307319
if isinstance(o, URIRef):
308320
return self.context.shrink_iri(o)
@@ -317,7 +329,9 @@ def type_coerce(self, o, coerce_type):
317329
else:
318330
return None
319331

320-
def to_raw_value(self, graph, s, o, nodemap):
332+
def to_raw_value(
333+
self, graph: Graph, s: IdentifiedNode, o: Identifier, nodemap: Dict[str, Any]
334+
):
321335
context = self.context
322336
coll = self.to_collection(graph, o)
323337
if coll is not None:
@@ -364,7 +378,7 @@ def to_raw_value(self, graph, s, o, nodemap):
364378
else:
365379
return v
366380

367-
def to_collection(self, graph, l_):
381+
def to_collection(self, graph: Graph, l_: Identifier):
368382
if l_ != RDF.nil and not graph.value(l_, RDF.first):
369383
return None
370384
list_nodes = []

0 commit comments

Comments
 (0)