Skip to content

Commit e44d849

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 4ded2eb commit e44d849

Some content is hidden

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

48 files changed

+1179
-509
lines changed

Taskfile.yml

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,20 @@ tasks:
117117
cmds:
118118
- "{{._PYTHON}} -m isort --check --diff ."
119119
- "{{._PYTHON}} -m black --check --diff ."
120-
- task: flake8
120+
# - task: flake8
121+
122+
123+
typecheck:
124+
desc: Check type hints
125+
cmds:
126+
- "{{._PYTHON}} -m mypy --show-error-context --show-error-codes"
121127

122128

123129
validate:static:
124130
desc: Perform static validation
125131
cmds:
126132
- task: lint
127-
- "{{._PYTHON}} -m mypy --show-error-context --show-error-codes"
133+
- task: typecheck
128134

129135
validate:fix:
130136
desc: Fix auto-fixable validation errors.

rdflib/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
"util",
8787
"plugin",
8888
"query",
89+
"_typing",
8990
]
9091

9192
import logging

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/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
@@ -111,11 +111,10 @@
111111
import itertools
112112
import logging
113113

114-
from rdflib import RDF, RDFS, BNode, Literal, Namespace, URIRef, Variable
115114
from rdflib.collection import Collection
116115
from rdflib.graph import Graph
117-
from rdflib.namespace import OWL, XSD, NamespaceManager
118-
from rdflib.term import Identifier
116+
from rdflib.namespace import OWL, RDF, RDFS, XSD, Namespace, NamespaceManager
117+
from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
119118
from rdflib.util import first
120119

121120
logger = logging.getLogger(__name__)

rdflib/graph.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -525,9 +525,7 @@ def triples(
525525
for _s, _o in p.eval(self, s, o):
526526
yield _s, p, _o
527527
else:
528-
# type error: Argument 1 to "triples" of "Store" has incompatible type "Tuple[Optional[Node], Optional[Node], Optional[Node]]"; expected "Tuple[Optional[IdentifiedNode], Optional[IdentifiedNode], Optional[Node]]"
529-
# NOTE on type error: This is because the store typing is too narrow, willbe fixed in subsequent PR.
530-
for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self): # type: ignore [arg-type]
528+
for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self):
531529
yield _s, _p, _o
532530

533531
def __getitem__(self, item):
@@ -1357,18 +1355,21 @@ def query(
13571355
query_object,
13581356
initNs,
13591357
initBindings,
1360-
self.default_union and "__UNION__" or self.identifier,
1358+
# type error: Argument 4 to "query" of "Store" has incompatible type "Union[Literal['__UNION__'], Node]"; expected "Identifier"
1359+
self.default_union and "__UNION__" or self.identifier, # type: ignore[arg-type]
13611360
**kwargs,
13621361
)
13631362
except NotImplementedError:
13641363
pass # store has no own implementation
13651364

1366-
if not isinstance(result, query.Result):
1365+
# type error: Subclass of "str" and "Result" cannot exist: would have incompatible method signatures
1366+
if not isinstance(result, query.Result): # type: ignore[unreachable]
13671367
result = plugin.get(cast(str, result), query.Result)
13681368
if not isinstance(processor, query.Processor):
13691369
processor = plugin.get(processor, query.Processor)(self)
13701370

1371-
return result(processor.query(query_object, initBindings, initNs, **kwargs))
1371+
# type error: Argument 1 to "Result" has incompatible type "Mapping[str, Any]"; expected "str"
1372+
return result(processor.query(query_object, initBindings, initNs, **kwargs)) # type: ignore[arg-type]
13721373

13731374
def update(
13741375
self,
@@ -1841,12 +1842,9 @@ def quads(
18411842

18421843
s, p, o, c = self._spoc(triple_or_quad)
18431844

1844-
# type error: Argument 1 to "triples" of "Store" has incompatible type "Tuple[Optional[Node], Optional[Node], Optional[Node]]"; expected "Tuple[Optional[IdentifiedNode], Optional[IdentifiedNode], Optional[Node]]"
1845-
# NOTE on type error: This is because the store typing is too narrow, willbe fixed in subsequent PR.
1846-
for (s, p, o), cg in self.store.triples((s, p, o), context=c): # type: ignore[arg-type]
1845+
for (s, p, o), cg in self.store.triples((s, p, o), context=c):
18471846
for ctx in cg:
1848-
# type error: Incompatible types in "yield" (actual type "Tuple[Optional[Node], Optional[Node], Optional[Node], Any]", expected type "Tuple[Node, Node, Node, Optional[Graph]]")
1849-
yield s, p, o, ctx # type: ignore[misc]
1847+
yield s, p, o, ctx
18501848

18511849
def triples_choices(self, triple, context=None):
18521850
"""Iterate over all the triples in the entire conjunctive graph"""
@@ -1878,7 +1876,8 @@ def contexts(
18781876
# the weirdness - see #225
18791877
yield context
18801878
else:
1881-
yield self.get_context(context)
1879+
# type error: Statement is unreachable
1880+
yield self.get_context(context) # type: ignore[unreachable]
18821881

18831882
def get_graph(self, identifier: Union[URIRef, BNode]) -> Union[Graph, None]:
18841883
"""Returns the graph identified by given identifier"""

rdflib/parser.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
if TYPE_CHECKING:
4040
from http.client import HTTPMessage, HTTPResponse
4141

42-
from rdflib import Graph
42+
from rdflib.graph import Graph
4343

4444
__all__ = [
4545
"Parser",
@@ -79,7 +79,11 @@ def read(self, *args, **kwargs):
7979
def read1(self, *args, **kwargs):
8080
if self.encoded is None:
8181
b = codecs.getencoder(self.encoding)(self.wrapped)
82-
self.encoded = BytesIO(b)
82+
# NOTE on pytype error: Looks like this may be an actual bug.
83+
# pytype error: Function BytesIO.__init__ was called with the wrong arguments
84+
# Expected: (self, initial_bytes: Union[bytearray, bytes, memoryview] = ...)
85+
# Actually passed: (self, initial_bytes: Tuple[bytes, int])
86+
self.encoded = BytesIO(b) # pytype: disable=wrong-arg-types
8387
return self.encoded.read1(*args, **kwargs)
8488

8589
def readinto(self, *args, **kwargs):
@@ -336,8 +340,8 @@ def create_input_source(
336340
publicID: Optional[str] = None,
337341
location: Optional[str] = None,
338342
file: Optional[Union[BinaryIO, TextIO]] = None,
339-
data: Union[str, bytes, dict] = None,
340-
format: str = None,
343+
data: Optional[Union[str, bytes, dict]] = None,
344+
format: Optional[str] = None,
341345
) -> InputSource:
342346
"""
343347
Return an appropriate InputSource instance for the given

rdflib/plugin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def plugins(name: Optional[str] = ..., kind: None = ...) -> Iterator[Plugin]:
158158

159159
def plugins(
160160
name: Optional[str] = None, kind: Optional[Type[PluginT]] = None
161-
) -> Iterator[Plugin]:
161+
) -> Iterator[Plugin[PluginT]]:
162162
"""
163163
A generator of the plugins.
164164

rdflib/plugins/parsers/hext.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77
import warnings
88
from typing import List, Union
99

10-
from rdflib import BNode, ConjunctiveGraph, Literal, URIRef
10+
from rdflib.graph import ConjunctiveGraph
1111
from rdflib.parser import Parser
12+
from rdflib.term import BNode, Literal, URIRef
1213

1314
__all__ = ["HextuplesParser"]
1415

rdflib/plugins/parsers/nquads.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
from codecs import getreader
2727

28-
from rdflib import ConjunctiveGraph
28+
from rdflib.graph import ConjunctiveGraph
2929

3030
# Build up from the NTriples parser:
3131
from rdflib.plugins.parsers.ntriples import (

0 commit comments

Comments
 (0)