Skip to content

Commit 92f43c3

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 fda98ec commit 92f43c3

Some content is hidden

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

51 files changed

+1252
-571
lines changed

Taskfile.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ tasks:
157157
vars: { CHECK: true }
158158
- task: black
159159
vars: { CHECK: true }
160-
- task: flake8
160+
# - task: flake8
161161

162162
validate:static:
163163
desc: Perform static validation

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 & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@
113113
from rdflib import OWL, RDF, RDFS, XSD, BNode, Literal, Namespace, URIRef, Variable
114114
from rdflib.collection import Collection
115115
from rdflib.graph import Graph
116-
from rdflib.namespace import NamespaceManager
117-
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
118118
from rdflib.util import first
119119

120120
logger = logging.getLogger(__name__)

rdflib/graph.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -534,9 +534,7 @@ def triples(
534534
for _s, _o in p.eval(self, s, o):
535535
yield _s, p, _o
536536
else:
537-
# 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]]"
538-
# NOTE on type error: This is because the store typing is too narrow, willbe fixed in subsequent PR.
539-
for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self): # type: ignore [arg-type]
537+
for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self):
540538
yield _s, _p, _o
541539

542540
def __getitem__(self, item):
@@ -1384,18 +1382,21 @@ def query(
13841382
query_object,
13851383
initNs,
13861384
initBindings,
1387-
self.default_union and "__UNION__" or self.identifier,
1385+
# type error: Argument 4 to "query" of "Store" has incompatible type "Union[Literal['__UNION__'], Node]"; expected "Identifier"
1386+
self.default_union and "__UNION__" or self.identifier, # type: ignore[arg-type]
13881387
**kwargs,
13891388
)
13901389
except NotImplementedError:
13911390
pass # store has no own implementation
13921391

1393-
if not isinstance(result, query.Result):
1392+
# type error: Subclass of "str" and "Result" cannot exist: would have incompatible method signatures
1393+
if not isinstance(result, query.Result): # type: ignore[unreachable]
13941394
result = plugin.get(cast(str, result), query.Result)
13951395
if not isinstance(processor, query.Processor):
13961396
processor = plugin.get(processor, query.Processor)(self)
13971397

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

14001401
def update(
14011402
self,
@@ -1868,12 +1869,9 @@ def quads(
18681869

18691870
s, p, o, c = self._spoc(triple_or_quad)
18701871

1871-
# 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]]"
1872-
# NOTE on type error: This is because the store typing is too narrow, willbe fixed in subsequent PR.
1873-
for (s, p, o), cg in self.store.triples((s, p, o), context=c): # type: ignore[arg-type]
1872+
for (s, p, o), cg in self.store.triples((s, p, o), context=c):
18741873
for ctx in cg:
1875-
# type error: Incompatible types in "yield" (actual type "Tuple[Optional[Node], Optional[Node], Optional[Node], Any]", expected type "Tuple[Node, Node, Node, Optional[Graph]]")
1876-
yield s, p, o, ctx # type: ignore[misc]
1874+
yield s, p, o, ctx
18771875

18781876
def triples_choices(self, triple, context=None):
18791877
"""Iterate over all the triples in the entire conjunctive graph"""
@@ -1905,7 +1903,8 @@ def contexts(
19051903
# the weirdness - see #225
19061904
yield context
19071905
else:
1908-
yield self.get_context(context)
1906+
# type error: Statement is unreachable
1907+
yield self.get_context(context) # type: ignore[unreachable]
19091908

19101909
def get_graph(self, identifier: Union[URIRef, BNode]) -> Union[Graph, None]:
19111910
"""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, # noqa: N803
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
@@ -167,7 +167,7 @@ def plugins(name: Optional[str] = ..., kind: None = ...) -> Iterator[Plugin]:
167167

168168
def plugins(
169169
name: Optional[str] = None, kind: Optional[Type[PluginT]] = None
170-
) -> Iterator[Plugin]:
170+
) -> Iterator[Plugin[PluginT]]:
171171
"""
172172
A generator of the plugins.
173173

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)