Skip to content

Commit c3e431c

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 eba1373 commit c3e431c

Some content is hidden

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

60 files changed

+1656
-743
lines changed

Taskfile.yml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,17 @@ tasks:
108108
- "{{._PYTHON}} -m isort --check --diff ."
109109
- "{{._PYTHON}} -m black --check --diff ."
110110

111+
typecheck:
112+
desc: Check type hints
113+
cmds:
114+
- "{{._PYTHON}} -m mypy --show-error-context --show-error-codes"
115+
116+
111117
validate:static:
112118
desc: Perform static validation
113119
cmds:
114120
- task: lint
115-
- "{{._PYTHON}} -m mypy --show-error-context --show-error-codes"
121+
- task: typecheck
116122

117123
validate:fix:
118124
desc: Fix auto-fixable validation errors.

rdflib/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
"VOID",
8585
"XSD",
8686
"util",
87+
"_typing",
8788
]
8889

8990
import logging
@@ -194,5 +195,5 @@
194195
assert plugin
195196
assert query
196197

197-
from rdflib import util
198+
from rdflib import _typing, util
198199
from rdflib.container import *

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/compare.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@
104104
Union,
105105
)
106106

107-
from rdflib.graph import ConjunctiveGraph, Graph, ReadOnlyGraphAggregate
107+
from rdflib.graph import ConjunctiveGraph, Graph, ReadOnlyGraphAggregate, _TripleType
108108
from rdflib.term import BNode, IdentifiedNode, Node, URIRef
109109

110110
if TYPE_CHECKING:
@@ -281,7 +281,6 @@ def copy(self):
281281
)
282282

283283

284-
_TripleT = List[Node]
285284
_HashT = Callable[[], "HASH"]
286285

287286

@@ -326,7 +325,9 @@ def _initial_color(self) -> List[Color]:
326325
self._neighbors[p].add(p)
327326
if len(bnodes) > 0:
328327
return [Color(list(bnodes), self.hashfunc, hash_cache=self._hash_cache)] + [
329-
Color([x], self.hashfunc, x, hash_cache=self._hash_cache)
328+
# type error: List item 0 has incompatible type "Union[IdentifiedNode, Literal]"; expected "IdentifiedNode"
329+
# type error: Argument 3 to "Color" has incompatible type "Union[IdentifiedNode, Literal]"; expected "Tuple[Tuple[Union[int, str], URIRef, Union[int, str]], ...]"
330+
Color([x], self.hashfunc, x, hash_cache=self._hash_cache) # type: ignore[list-item, arg-type]
330331
for x in others
331332
]
332333
else:
@@ -521,7 +522,7 @@ def canonical_triples(self, stats: Optional[Stats] = None):
521522

522523
def _canonicalize_bnodes(
523524
self,
524-
triple: Tuple[IdentifiedNode, IdentifiedNode, Node],
525+
triple: "_TripleType",
525526
labels: Dict[Node, str],
526527
):
527528
for term in triple:
@@ -531,7 +532,7 @@ def _canonicalize_bnodes(
531532
yield term
532533

533534

534-
def to_isomorphic(graph):
535+
def to_isomorphic(graph: Graph) -> IsomorphicGraph:
535536
if isinstance(graph, IsomorphicGraph):
536537
return graph
537538
result = IsomorphicGraph()
@@ -541,7 +542,7 @@ def to_isomorphic(graph):
541542
return result
542543

543544

544-
def isomorphic(graph1, graph2):
545+
def isomorphic(graph1: Graph, graph2: Graph) -> bool:
545546
"""Compare graph for equality.
546547
547548
Uses an algorithm to compute unique hashes which takes bnodes into account.
@@ -577,7 +578,9 @@ def isomorphic(graph1, graph2):
577578
return gd1 == gd2
578579

579580

580-
def to_canonical_graph(g1, stats=None):
581+
def to_canonical_graph(
582+
g1: Graph, stats: Optional[Stats] = None
583+
) -> ReadOnlyGraphAggregate:
581584
"""Creates a canonical, read-only graph.
582585
583586
Creates a canonical, read-only graph where all bnode id:s are based on
@@ -588,7 +591,7 @@ def to_canonical_graph(g1, stats=None):
588591
return ReadOnlyGraphAggregate([graph])
589592

590593

591-
def graph_diff(g1, g2):
594+
def graph_diff(g1: Graph, g2: Graph) -> Tuple[Graph, Graph, Graph]:
592595
"""Returns three sets of triples: "in both", "in first" and "in second"."""
593596
# bnodes have deterministic values in canonical graphs:
594597
cg1 = to_canonical_graph(g1)
@@ -602,7 +605,7 @@ def graph_diff(g1, g2):
602605
_MOCK_BNODE = BNode()
603606

604607

605-
def similar(g1, g2):
608+
def similar(g1: Graph, g2: Graph):
606609
"""Checks if the two graphs are "similar".
607610
608611
Checks if the two graphs are "similar", by comparing sorted triples where
@@ -615,12 +618,12 @@ def similar(g1, g2):
615618
return all(t1 == t2 for (t1, t2) in _squashed_graphs_triples(g1, g2))
616619

617620

618-
def _squashed_graphs_triples(g1, g2):
621+
def _squashed_graphs_triples(g1: Graph, g2: Graph):
619622
for (t1, t2) in zip(sorted(_squash_graph(g1)), sorted(_squash_graph(g2))):
620623
yield t1, t2
621624

622625

623-
def _squash_graph(graph):
626+
def _squash_graph(graph: Graph):
624627
return (_squash_bnodes(triple) for triple in graph)
625628

626629

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

0 commit comments

Comments
 (0)