Skip to content

Commit 2f8fe97

Browse files
committed
iwana-20220126T2212-typing: checkpoint 20230910T155719 - 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 2f8fe97

33 files changed

+489
-228
lines changed

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/extras/cmdlineutils.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
from __future__ import annotations
2+
13
import codecs
24
import getopt
35
import sys
46
import time
7+
from typing import TextIO, Union
58

69
import rdflib
710
from rdflib.util import guess_format
@@ -40,6 +43,7 @@ def main(target, _help=_help, options="", stdin=True):
4043
else:
4144
f = None
4245

46+
out: Union[TextIO, codecs.StreamReaderWriter]
4347
if "-o" in dargs:
4448
sys.stderr.write("Output to %s\n" % dargs["-o"])
4549
out = codecs.open(dargs["-o"], "w", "utf-8")

rdflib/extras/infixowl.py

Lines changed: 43 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,14 @@
112112
>>> print(g.serialize(format='pretty-xml')) # doctest: +SKIP
113113
114114
"""
115+
from __future__ import annotations
115116

116117
import itertools
117118
import logging
119+
from typing import Iterable, Union
118120

119121
from rdflib.collection import Collection
120-
from rdflib.graph import Graph
122+
from rdflib.graph import Graph, _ObjectType
121123
from rdflib.namespace import OWL, RDF, RDFS, XSD, Namespace, NamespaceManager
122124
from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
123125
from rdflib.util import first
@@ -432,11 +434,11 @@ def replace(self, other):
432434
self.graph.add((s, p, classOrIdentifier(other)))
433435
self.delete()
434436

435-
def _get_type(self):
437+
def _get_type(self) -> Iterable[_ObjectType]:
436438
for _t in self.graph.objects(subject=self.identifier, predicate=RDF.type):
437439
yield _t
438440

439-
def _set_type(self, kind):
441+
def _set_type(self, kind: Union[Individual, Identifier, Iterable[_ObjectType]]):
440442
if not kind:
441443
return
442444
if isinstance(kind, (Individual, Identifier)):
@@ -462,10 +464,10 @@ def _delete_type(self):
462464

463465
type = property(_get_type, _set_type, _delete_type)
464466

465-
def _get_identifier(self):
467+
def _get_identifier(self) -> Identifier:
466468
return self.__identifier
467469

468-
def _set_identifier(self, i):
470+
def _set_identifier(self, i: Identifier):
469471
assert i
470472
if i != self.__identifier:
471473
oldstatements_out = [
@@ -492,11 +494,13 @@ def _set_identifier(self, i):
492494

493495
identifier = property(_get_identifier, _set_identifier)
494496

495-
def _get_sameAs(self): # noqa: N802
497+
def _get_sameAs(self) -> Iterable[_ObjectType]: # noqa: N802
496498
for _t in self.graph.objects(subject=self.identifier, predicate=OWL.sameAs):
497499
yield _t
498500

499-
def _set_sameAs(self, term): # noqa: N802
501+
def _set_sameAs( # noqa: N802
502+
self, term: Union[Individual, Identifier, Iterable[_ObjectType]]
503+
):
500504
# if not kind:
501505
# return
502506
if isinstance(term, (Individual, Identifier)):
@@ -1305,7 +1309,8 @@ def isPrimitive(self): # noqa: N802
13051309
# sc = list(self.subClassOf)
13061310
ec = list(self.equivalentClass)
13071311
for _boolclass, p, rdf_list in self.graph.triples_choices(
1308-
(self.identifier, [OWL.intersectionOf, OWL.unionOf], None)
1312+
# type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
1313+
(self.identifier, [OWL.intersectionOf, OWL.unionOf], None) # type: ignore[arg-type]
13091314
):
13101315
ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
13111316
for _e in ec:
@@ -1331,7 +1336,8 @@ def __repr__(self, full=False, normalization=True):
13311336
sc = list(self.subClassOf)
13321337
ec = list(self.equivalentClass)
13331338
for _boolclass, p, rdf_list in self.graph.triples_choices(
1334-
(self.identifier, [OWL.intersectionOf, OWL.unionOf], None)
1339+
# type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
1340+
(self.identifier, [OWL.intersectionOf, OWL.unionOf], None) # type: ignore[arg-type]
13351341
):
13361342
ec.append(manchesterSyntax(rdf_list, self.graph, boolean=p))
13371343
dc = list(self.disjointWith)
@@ -1340,7 +1346,9 @@ def __repr__(self, full=False, normalization=True):
13401346
dc.append(c)
13411347
klasskind = ""
13421348
label = list(self.graph.objects(self.identifier, RDFS.label))
1343-
label = label and "(" + label[0] + ")" or ""
1349+
# type error: Incompatible types in assignment (expression has type "str", variable has type "List[Node]")
1350+
# type error: Unsupported operand types for + ("str" and "Node")
1351+
label = label and "(" + label[0] + ")" or "" # type: ignore[assignment, operator]
13441352
if sc:
13451353
if full:
13461354
scjoin = "\n "
@@ -1421,7 +1429,9 @@ def __init__(self, rdf_list, members=None, graph=None):
14211429
self._rdfList = Collection(
14221430
self.graph, BNode(), [classOrIdentifier(m) for m in members]
14231431
)
1424-
self.graph.add((self.identifier, self._operator, self._rdfList.uri))
1432+
# type error: "OWLRDFListProxy" has no attribute "identifier"
1433+
# type error: "OWLRDFListProxy" has no attribute "_operator"
1434+
self.graph.add((self.identifier, self._operator, self._rdfList.uri)) # type: ignore[attr-defined]
14251435

14261436
def __eq__(self, other):
14271437
"""
@@ -1439,7 +1449,8 @@ def __eq__(self, other):
14391449
return False
14401450
return True
14411451
else:
1442-
return self.identifier == other.identifier
1452+
# type error: "OWLRDFListProxy" has no attribute "identifier"
1453+
return self.identifier == other.identifier # type: ignore[attr-defined]
14431454

14441455
# Redirect python list accessors to the underlying Collection instance
14451456
def __len__(self):
@@ -1777,8 +1788,10 @@ def __init__(
17771788
elif isinstance(restriction_range, Class):
17781789
self.restrictionRange = classOrIdentifier(restriction_range)
17791790
else:
1780-
self.restrictionRange = first(
1781-
self.graph.objects(self.identifier, restriction_type)
1791+
# error: Incompatible types in assignment (expression has type "Optional[Identifier]", variable has type "Identifier")
1792+
self.restrictionRange = first( # type: ignore[assignment]
1793+
# type error: Argument 1 to "first" has incompatible type "Generator[Node, None, None]"; expected "Iterable[Identifier]"
1794+
self.graph.objects(self.identifier, restriction_type) # type: ignore[arg-type]
17821795
)
17831796
if (
17841797
self.identifier,
@@ -1834,7 +1847,8 @@ def __eq__(self, other):
18341847
if isinstance(other, Restriction):
18351848
return (
18361849
other.onProperty == self.onProperty
1837-
and other.restriction_range == self.restrictionRange
1850+
# type error: "Restriction" has no attribute "restriction_range"; maybe "restrictionRange"?
1851+
and other.restriction_range == self.restrictionRange # type: ignore[attr-defined]
18381852
)
18391853
else:
18401854
return False
@@ -1999,9 +2013,11 @@ def _del_mincardinality(self):
19992013

20002014
def restrictionKind(self): # noqa: N802
20012015
for s, p, o in self.graph.triples_choices(
2002-
(self.identifier, self.restrictionKinds, None)
2016+
# type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, List[URIRef], None]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
2017+
(self.identifier, self.restrictionKinds, None) # type: ignore[arg-type]
20032018
):
2004-
return p.split(str(OWL))[-1]
2019+
# type error: "Node" has no attribute "split"
2020+
return p.split(str(OWL))[-1] # type: ignore[attr-defined]
20052021
return None
20062022

20072023
def __repr__(self):
@@ -2155,9 +2171,11 @@ def __repr__(self):
21552171
% (self.qname, first(self.comment) and first(self.comment) or "")
21562172
)
21572173
if first(self.inverseOf):
2158-
two_link_inverse = first(first(self.inverseOf).inverseOf)
2174+
# type error: Item "None" of "Optional[Any]" has no attribute "inverseOf"
2175+
two_link_inverse = first(first(self.inverseOf).inverseOf) # type: ignore[union-attr]
21592176
if two_link_inverse and two_link_inverse.identifier == self.identifier:
2160-
inverserepr = first(self.inverseOf).qname
2177+
# type error: Item "None" of "Optional[Any]" has no attribute "qname"
2178+
inverserepr = first(self.inverseOf).qname # type: ignore[union-attr]
21612179
else:
21622180
inverserepr = repr(first(self.inverseOf))
21632181
rt.append(
@@ -2168,7 +2186,8 @@ def __repr__(self):
21682186
)
21692187
)
21702188
for _s, _p, roletype in self.graph.triples_choices(
2171-
(
2189+
# type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Any, URIRef, List[URIRef]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]"
2190+
( # type: ignore[arg-type]
21722191
self.identifier,
21732192
RDF.type,
21742193
[
@@ -2178,7 +2197,8 @@ def __repr__(self):
21782197
],
21792198
)
21802199
):
2181-
rt.append(str(roletype.split(str(OWL))[-1]))
2200+
# type error: "Node" has no attribute "split"
2201+
rt.append(str(roletype.split(str(OWL))[-1])) # type: ignore[attr-defined]
21822202
else:
21832203
rt.append(
21842204
"DatatypeProperty( %s %s"
@@ -2228,7 +2248,8 @@ def canonicalName(term, g): # noqa: N802
22282248
]
22292249
)
22302250
)
2231-
rt = "\n".join([expr for expr in rt if expr])
2251+
# type error: Incompatible types in assignment (expression has type "str", variable has type "List[str]")
2252+
rt = "\n".join([expr for expr in rt if expr]) # type: ignore[assignment]
22322253
rt += "\n)"
22332254
return rt
22342255

rdflib/graph.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,8 @@ def __getitem__(self, item):
655655
return (s, p, o) in self
656656

657657
elif isinstance(item, (Path, Node)):
658-
return self.predicate_objects(item)
658+
# type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[Path, Node]"; expected "Optional[Node]"
659+
return self.predicate_objects(item) # type: ignore[arg-type]
659660

660661
else:
661662
raise TypeError(

rdflib/parser.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def __init__(self, wrapped: str, encoding="utf-8"):
7070
super(BytesIOWrapper, self).__init__()
7171
self.wrapped = wrapped
7272
self.encoding = encoding
73-
self.encoded = None
73+
self.encoded: Optional[BytesIO] = None
7474

7575
def read(self, *args, **kwargs):
7676
if self.encoded is None:
@@ -81,7 +81,8 @@ def read(self, *args, **kwargs):
8181
def read1(self, *args, **kwargs):
8282
if self.encoded is None:
8383
b = codecs.getencoder(self.encoding)(self.wrapped)
84-
self.encoded = BytesIO(b)
84+
# type error: Argument 1 to "BytesIO" has incompatible type "Tuple[bytes, int]"; expected "Buffer"
85+
self.encoded = BytesIO(b) # type: ignore[arg-type]
8586
return self.encoded.read1(*args, **kwargs)
8687

8788
def readinto(self, *args, **kwargs):

0 commit comments

Comments
 (0)