Skip to content

Commit 353ea9b

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. checkpoint checkpoint checkpoint checkpoint
1 parent 5c3c78a commit 353ea9b

32 files changed

+320
-153
lines changed

docs/conf.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,9 @@ def find_version(filename):
323323
("py:class", "_TripleOrTriplePathType"),
324324
("py:class", "TextIO"),
325325
("py:class", "Message"),
326+
("py:class", "HTTPResponse"),
327+
("py:class", "HTTPMessage"),
328+
("py:class", "EntryPoint"),
326329
]
327330
)
328331

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)}")

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
@@ -243,7 +243,7 @@ def append(self, item: Node) -> Collection:
243243
self.graph.add((end, RDF.rest, RDF.nil))
244244
return self
245245

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

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

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

rdflib/compat.py

Lines changed: 2 additions & 0 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

rdflib/plugins/parsers/jsonld.py

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

rdflib/plugins/serializers/rdfxml.py

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import xml.dom.minidom
2-
from typing import IO, Dict, Optional, Set
2+
from typing import IO, Dict, Generator, Optional, Set, Tuple
33
from xml.sax.saxutils import escape, quoteattr
44

55
from rdflib.collection import Collection
@@ -20,13 +20,14 @@ class XMLSerializer(Serializer):
2020
def __init__(self, store: Graph):
2121
super(XMLSerializer, self).__init__(store)
2222

23-
def __bindings(self):
23+
def __bindings(self) -> Generator[Tuple[str, URIRef], None, None]:
2424
store = self.store
2525
nm = store.namespace_manager
26-
bindings = {}
26+
bindings: Dict[str, URIRef] = {}
2727

2828
for predicate in set(store.predicates()):
29-
prefix, namespace, name = nm.compute_qname_strict(predicate)
29+
# type error: Argument 1 to "compute_qname_strict" of "NamespaceManager" has incompatible type "Node"; expected "str"
30+
prefix, namespace, name = nm.compute_qname_strict(predicate) # type: ignore[arg-type]
3031
bindings[prefix] = URIRef(namespace)
3132

3233
RDFNS = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
@@ -45,7 +46,7 @@ def serialize(
4546
base: Optional[str] = None,
4647
encoding: Optional[str] = None,
4748
**args,
48-
):
49+
) -> None:
4950
# if base is given here, use that, if not and a base is set for the graph use that
5051
if base is not None:
5152
self.base = base
@@ -82,7 +83,8 @@ def serialize(
8283

8384
# write out triples by subject
8485
for subject in self.store.subjects():
85-
self.subject(subject, 1)
86+
# type error: Argument 1 to "subject" of "XMLSerializer" has incompatible type "Node"; expected "Identifier"
87+
self.subject(subject, 1) # type: ignore[arg-type]
8688

8789
# endRDF
8890
write("</rdf:RDF>\n")
@@ -91,7 +93,7 @@ def serialize(
9193
# self.__serialized = None
9294
del self.__serialized
9395

94-
def subject(self, subject, depth=1):
96+
def subject(self, subject: Identifier, depth: int = 1) -> None:
9597
if subject not in self.__serialized:
9698
self.__serialized[subject] = 1
9799

@@ -110,13 +112,17 @@ def subject(self, subject, depth=1):
110112
write(">\n")
111113

112114
for predicate, object in self.store.predicate_objects(subject):
113-
self.predicate(predicate, object, depth + 1)
115+
# type error: Argument 1 to "predicate" of "XMLSerializer" has incompatible type "Node"; expected "Identifier"
116+
# type error: Argument 2 to "predicate" of "XMLSerializer" has incompatible type "Node"; expected "Identifier"
117+
self.predicate(predicate, object, depth + 1) # type: ignore[arg-type]
114118
write("%s</%s>\n" % (indent, element_name))
115119

116120
else:
117121
write("/>\n")
118122

119-
def predicate(self, predicate, object, depth=1):
123+
def predicate(
124+
self, predicate: Identifier, object: Identifier, depth: int = 1
125+
) -> None:
120126
write = self.write
121127
indent = " " * depth
122128
qname = self.store.namespace_manager.qname_strict(predicate)
@@ -150,7 +156,7 @@ def predicate(self, predicate, object, depth=1):
150156

151157

152158
# TODO:
153-
def fix(val):
159+
def fix(val: str) -> str:
154160
"strip off _: from nodeIDs... as they are not valid NCNames"
155161
if val.startswith("_:"):
156162
return val[2:]
@@ -169,7 +175,7 @@ def serialize(
169175
base: Optional[str] = None,
170176
encoding: Optional[str] = None,
171177
**args,
172-
):
178+
) -> None:
173179
self.__serialized: Dict[Identifier, int] = {}
174180
store = self.store
175181
# if base is given here, use that, if not and a base is set for the graph use that
@@ -236,7 +242,7 @@ def serialize(
236242
# Set to None so that the memory can get garbage collected.
237243
self.__serialized = None # type: ignore[assignment]
238244

239-
def subject(self, subject: IdentifiedNode, depth: int = 1):
245+
def subject(self, subject: Identifier, depth: int = 1):
240246
store = self.store
241247
writer = self.writer
242248

@@ -257,7 +263,8 @@ def subject(self, subject: IdentifiedNode, depth: int = 1):
257263
type = None
258264

259265
element = type or RDFVOC.Description
260-
writer.push(element)
266+
# type error: Argument 1 to "push" of "XMLWriter" has incompatible type "Node"; expected "str"
267+
writer.push(element) # type: ignore[arg-type]
261268

262269
if isinstance(subject, BNode):
263270

@@ -277,9 +284,12 @@ def subj_as_obj_more_than(ceil):
277284
if (subject, None, None) in store:
278285
for predicate, object in store.predicate_objects(subject):
279286
if not (predicate == RDF.type and object == type):
280-
self.predicate(predicate, object, depth + 1)
287+
# type error: Argument 1 to "predicate" of "PrettyXMLSerializer" has incompatible type "Node"; expected "Identifier"
288+
# type error: Argument 2 to "predicate" of "PrettyXMLSerializer" has incompatible type "Node"; expected "Identifier"
289+
self.predicate(predicate, object, depth + 1) # type: ignore[arg-type]
281290

282-
writer.pop(element)
291+
# type error: Argument 1 to "pop" of "XMLWriter" has incompatible type "Node"; expected "Optional[str]"
292+
writer.pop(element) # type: ignore[arg-type]
283293

284294
elif subject in self.forceRDFAbout:
285295
# TODO FIXME?: this looks like a duplicate of first condition
@@ -288,7 +298,9 @@ def subj_as_obj_more_than(ceil):
288298
writer.pop(RDFVOC.Description)
289299
self.forceRDFAbout.remove(subject) # type: ignore[arg-type]
290300

291-
def predicate(self, predicate, object, depth=1):
301+
def predicate(
302+
self, predicate: Identifier, object: Identifier, depth: int = 1
303+
) -> None:
292304
writer = self.writer
293305
store = self.store
294306
writer.push(predicate)
@@ -338,14 +350,17 @@ def predicate(self, predicate, object, depth=1):
338350
for item in col:
339351
if isinstance(item, URIRef):
340352
self.forceRDFAbout.add(item)
341-
self.subject(item)
353+
# type error: Argument 1 to "subject" of "PrettyXMLSerializer" has incompatible type "Node"; expected "Identifier"
354+
self.subject(item) # type: ignore[arg-type]
342355

343356
if not isinstance(item, URIRef):
344-
self.__serialized[item] = 1
357+
# type error: Invalid index type "Node" for "Dict[Identifier, int]"; expected type "Identifier"
358+
self.__serialized[item] = 1 # type: ignore[index]
345359
else:
346360
if first(
347361
store.triples_choices(
348-
(object, RDF.type, [OWL_NS.Class, RDFS.Class])
362+
# type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Identifier, URIRef, List[URIRef]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
363+
(object, RDF.type, [OWL_NS.Class, RDFS.Class]) # type: ignore[arg-type]
349364
)
350365
) and isinstance(object, URIRef):
351366
writer.attribute(RDFVOC.resource, self.relativize(object))

rdflib/plugins/serializers/trig.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
See <http://www.w3.org/TR/trig/> for syntax specification.
44
"""
55

6-
from typing import IO, TYPE_CHECKING, Dict, List, Optional, Tuple, Union
6+
from typing import IO, TYPE_CHECKING, Dict, List, Optional, Tuple
77

88
from rdflib.graph import ConjunctiveGraph, Graph
99
from rdflib.plugins.serializers.turtle import TurtleSerializer
@@ -19,7 +19,7 @@ class TrigSerializer(TurtleSerializer):
1919
short_name = "trig"
2020
indentString = 4 * " "
2121

22-
def __init__(self, store: Union[Graph, ConjunctiveGraph]):
22+
def __init__(self, store: Graph):
2323
self.default_context: Optional[Node]
2424
if store.context_aware:
2525
if TYPE_CHECKING:

0 commit comments

Comments
 (0)