Skip to content

Commit a78c96d

Browse files
committed
iwana-20220126T2212-typing: checkpoint 20230910T155719
1 parent ea19541 commit a78c96d

File tree

11 files changed

+119
-60
lines changed

11 files changed

+119
-60
lines changed

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):

rdflib/plugins/serializers/hext.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ def _context(self, context):
138138
if context.identifier == "urn:x-rdflib:default":
139139
return ""
140140
elif context is not None and self.default_context is not None:
141-
if context.identifier == self.default_context.identifier:
141+
# type error: "Node" has no attribute "identifier"
142+
if context.identifier == self.default_context.identifier: # type: ignore[attr-defined]
142143
return ""
143144
return context.identifier

rdflib/plugins/serializers/jsonld.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
import warnings
4040
from typing import IO, TYPE_CHECKING, Any, Dict, List, Optional
4141

42-
from rdflib.graph import Graph
42+
from rdflib.graph import Graph, _ObjectType
4343
from rdflib.namespace import RDF, XSD
4444
from rdflib.serializer import Serializer
4545
from rdflib.term import BNode, IdentifiedNode, Identifier, Literal, URIRef
@@ -154,7 +154,8 @@ def convert(self, graph: Graph):
154154
if graph.context_aware:
155155
default_graph = Graph()
156156
graphs = [default_graph]
157-
for g in graph.contexts():
157+
# type error: "Graph" has no attribute "contexts"
158+
for g in graph.contexts(): # type: ignore[attr-defined]
158159
if isinstance(g.identifier, URIRef):
159160
graphs.append(g)
160161
else:
@@ -227,7 +228,9 @@ def process_subject(self, graph: Graph, s: IdentifiedNode, nodemap):
227228
nodemap[node_id] = node
228229

229230
for p, o in graph.predicate_objects(s):
230-
self.add_to_node(graph, s, p, o, node, nodemap)
231+
# type error: Argument 3 to "add_to_node" of "Converter" has incompatible type "Node"; expected "IdentifiedNode"
232+
# type error: Argument 4 to "add_to_node" of "Converter" has incompatible type "Node"; expected "Identifier"
233+
self.add_to_node(graph, s, p, o, node, nodemap) # type: ignore[arg-type]
231234

232235
return node
233236

@@ -250,7 +253,9 @@ def add_to_node(
250253
containers = [LIST, None] if graph.value(o, RDF.first) else [None]
251254
for container in containers:
252255
for coercion in (ID, VOCAB, UNDEF):
253-
term = context.find_term(str(p), coercion, container)
256+
# type error: Argument 2 to "find_term" of "Context" has incompatible type "object"; expected "Union[str, Defined, None]"
257+
# type error: Argument 3 to "find_term" of "Context" has incompatible type "Optional[str]"; expected "Union[Defined, str]"
258+
term = context.find_term(str(p), coercion, container) # type: ignore[arg-type]
254259
if term:
255260
break
256261
if term:
@@ -264,10 +269,12 @@ def add_to_node(
264269

265270
if term.type:
266271
node = self.type_coerce(o, term.type)
267-
elif term.language and o.language == term.language:
268-
node = str(o)
269-
elif context.language and (term.language is None and o.language is None):
272+
# type error: "Identifier" has no attribute "language"
273+
elif term.language and o.language == term.language: # type: ignore[attr-defined]
270274
node = str(o)
275+
# type error: Right operand of "and" is never evaluated
276+
elif context.language and (term.language is None and o.language is None): # type: ignore[unreachable]
277+
node = str(o) # type: ignore[unreachable]
271278

272279
if LIST in term.container:
273280
node = [
@@ -314,7 +321,7 @@ def add_to_node(
314321
value = node
315322
s_node[p_key] = value
316323

317-
def type_coerce(self, o: IdentifiedNode, coerce_type: str):
324+
def type_coerce(self, o: Identifier, coerce_type: str):
318325
if coerce_type == ID:
319326
if isinstance(o, URIRef):
320327
return self.context.shrink_iri(o)
@@ -373,15 +380,16 @@ def to_raw_value(
373380
}
374381
elif o.language and o.language != context.language:
375382
return {context.lang_key: o.language, context.value_key: v}
376-
elif not context.active or context.language and not o.language:
383+
# type error: Right operand of "and" is never evaluated
384+
elif not context.active or context.language and not o.language: # type: ignore[unreachable]
377385
return {context.value_key: v}
378386
else:
379387
return v
380388

381389
def to_collection(self, graph: Graph, l_: Identifier):
382390
if l_ != RDF.nil and not graph.value(l_, RDF.first):
383391
return None
384-
list_nodes = []
392+
list_nodes: List[Optional[_ObjectType]] = []
385393
chain = set([l_])
386394
while l_:
387395
if l_ == RDF.nil:
@@ -397,7 +405,8 @@ def to_collection(self, graph: Graph, l_: Identifier):
397405
elif p != RDF.type or o != RDF.List:
398406
return None
399407
list_nodes.append(first)
400-
l_ = rest
408+
# type error: Incompatible types in assignment (expression has type "Optional[Node]", variable has type "Identifier")
409+
l_ = rest # type: ignore[assignment]
401410
if l_ in chain:
402411
return None
403412
chain.add(l_)

rdflib/plugins/sparql/aggregates.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,8 @@ class Sample(Accumulator):
227227
def __init__(self, aggregation):
228228
super(Sample, self).__init__(aggregation)
229229
# DISTINCT would not change the value
230-
self.use_row = self.dont_care
230+
# type error: Cannot assign to a method
231+
self.use_row = self.dont_care # type: ignore[method-assign]
231232

232233
def update(self, row: FrozenBindings, aggregator: Aggregator) -> None:
233234
try:

rdflib/resource.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ def __le__(self, other: object) -> bool:
341341
def __ge__(self, other: object) -> bool:
342342
return not self < other
343343

344-
def __unicode__(self):
344+
def __unicode__(self) -> str:
345345
return str(self._identifier)
346346

347347
def add(self, p: _PredicateType, o: _ObjectType):
@@ -352,13 +352,13 @@ def add(self, p: _PredicateType, o: _ObjectType):
352352

353353
def remove(
354354
self, p: _PredicateType, o: Optional[Union[_ObjectType, Resource]] = None
355-
):
355+
) -> None:
356356
if isinstance(o, Resource):
357357
o = o._identifier
358358

359359
self._graph.remove((self._identifier, p, o))
360360

361-
def set(self, p: _PredicateType, o: _ObjectType):
361+
def set(self, p: _PredicateType, o: _ObjectType) -> None:
362362
if isinstance(o, Resource):
363363
o = o._identifier
364364

@@ -405,7 +405,8 @@ def transitive_subjects(self, predicate, remember=None):
405405
)
406406

407407
def qname(self):
408-
return self._graph.qname(self._identifier)
408+
# type error: Argument 1 to "qname" of "Graph" has incompatible type "Node"; expected "str"
409+
return self._graph.qname(self._identifier) # type: ignore[arg-type]
409410

410411
def _resource_pairs(self, pairs):
411412
for s1, s2 in pairs:
@@ -458,7 +459,8 @@ def __getitem__(self, item):
458459
else:
459460
return (self.identifier, p, o) in self._graph
460461
elif isinstance(item, (Node, Path)):
461-
return self.objects(item)
462+
# type error: Argument 1 to "objects" of "Resource" has incompatible type "Union[Node, Path]"; expected "Optional[Node]"
463+
return self.objects(item) # type: ignore[arg-type]
462464
else:
463465
raise TypeError(
464466
"You can only index a resource by a single rdflib term, a slice of rdflib terms, not %s (%s)"

0 commit comments

Comments
 (0)