Skip to content

Commit 955b41f

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 fdc6479 commit 955b41f

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

+1640
-738
lines changed

docs/conf.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
extensions = [
3030
"sphinxcontrib.apidoc",
3131
"sphinx.ext.autodoc",
32-
#'sphinx.ext.autosummary',
32+
# 'sphinx.ext.autosummary',
33+
"sphinx_autodoc_typehints",
3334
"sphinx.ext.doctest",
3435
"sphinx.ext.intersphinx",
3536
"sphinx.ext.todo",
@@ -42,8 +43,14 @@
4243

4344
apidoc_module_dir = "../rdflib"
4445
apidoc_output_dir = "apidocs"
46+
47+
# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
4548
autodoc_default_options = {"special-members": True}
46-
autodoc_typehints = "both"
49+
# autodoc_typehints = "both"
50+
# typehints_defaults = "braces"
51+
52+
always_document_param_types = True
53+
4754

4855
autosummary_generate = True
4956

@@ -243,9 +250,3 @@ def find_version(filename):
243250
html_experimental_html5_writer = True
244251

245252
needs_sphinx = "4.1.2"
246-
247-
suppress_warnings = [
248-
# This is here to prevent:
249-
# "WARNING: more than one target found for cross-reference"
250-
"ref.python",
251-
]

docs/sphinx-requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ myst-parser
33
sphinx<5
44
sphinxcontrib-apidoc
55
sphinxcontrib-kroki
6+
sphinx-autodoc-typehints

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def test():
267267
if __name__ == "__main__":
268268
test()
269269

270-
from rdflib import Graph
270+
from rdflib.graph import Graph
271271

272272
g = Graph()
273273

rdflib/compare.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@
110110
if TYPE_CHECKING:
111111
from _hashlib import HASH
112112

113+
from rdflib._typing import _TripleType
114+
113115

114116
def _total_seconds(td):
115117
result = td.days * 24 * 60 * 60
@@ -281,7 +283,6 @@ def copy(self):
281283
)
282284

283285

284-
_TripleT = List[Node]
285286
_HashT = Callable[[], "HASH"]
286287

287288

@@ -326,7 +327,9 @@ def _initial_color(self) -> List[Color]:
326327
self._neighbors[p].add(p)
327328
if len(bnodes) > 0:
328329
return [Color(list(bnodes), self.hashfunc, hash_cache=self._hash_cache)] + [
329-
Color([x], self.hashfunc, x, hash_cache=self._hash_cache)
330+
# type error: List item 0 has incompatible type "Union[IdentifiedNode, Literal]"; expected "IdentifiedNode"
331+
# type error: Argument 3 to "Color" has incompatible type "Union[IdentifiedNode, Literal]"; expected "Tuple[Tuple[Union[int, str], URIRef, Union[int, str]], ...]"
332+
Color([x], self.hashfunc, x, hash_cache=self._hash_cache) # type: ignore[list-item, arg-type]
330333
for x in others
331334
]
332335
else:
@@ -521,7 +524,7 @@ def canonical_triples(self, stats: Optional[Stats] = None):
521524

522525
def _canonicalize_bnodes(
523526
self,
524-
triple: Tuple[IdentifiedNode, IdentifiedNode, Node],
527+
triple: "_TripleType",
525528
labels: Dict[Node, str],
526529
):
527530
for term in triple:
@@ -531,7 +534,7 @@ def _canonicalize_bnodes(
531534
yield term
532535

533536

534-
def to_isomorphic(graph):
537+
def to_isomorphic(graph: Graph) -> IsomorphicGraph:
535538
if isinstance(graph, IsomorphicGraph):
536539
return graph
537540
result = IsomorphicGraph()
@@ -541,7 +544,7 @@ def to_isomorphic(graph):
541544
return result
542545

543546

544-
def isomorphic(graph1, graph2):
547+
def isomorphic(graph1: Graph, graph2: Graph) -> bool:
545548
"""Compare graph for equality.
546549
547550
Uses an algorithm to compute unique hashes which takes bnodes into account.
@@ -577,7 +580,9 @@ def isomorphic(graph1, graph2):
577580
return gd1 == gd2
578581

579582

580-
def to_canonical_graph(g1, stats=None):
583+
def to_canonical_graph(
584+
g1: Graph, stats: Optional[Stats] = None
585+
) -> ReadOnlyGraphAggregate:
581586
"""Creates a canonical, read-only graph.
582587
583588
Creates a canonical, read-only graph where all bnode id:s are based on
@@ -588,7 +593,10 @@ def to_canonical_graph(g1, stats=None):
588593
return ReadOnlyGraphAggregate([graph])
589594

590595

591-
def graph_diff(g1, g2):
596+
# _GraphT = TypeVar("_GraphT", bound=Graph)
597+
598+
599+
def graph_diff(g1: Graph, g2: Graph) -> Tuple[Graph, Graph, Graph]:
592600
"""Returns three sets of triples: "in both", "in first" and "in second"."""
593601
# bnodes have deterministic values in canonical graphs:
594602
cg1 = to_canonical_graph(g1)
@@ -602,7 +610,7 @@ def graph_diff(g1, g2):
602610
_MOCK_BNODE = BNode()
603611

604612

605-
def similar(g1, g2):
613+
def similar(g1: Graph, g2: Graph):
606614
"""Checks if the two graphs are "similar".
607615
608616
Checks if the two graphs are "similar", by comparing sorted triples where
@@ -615,12 +623,12 @@ def similar(g1, g2):
615623
return all(t1 == t2 for (t1, t2) in _squashed_graphs_triples(g1, g2))
616624

617625

618-
def _squashed_graphs_triples(g1, g2):
626+
def _squashed_graphs_triples(g1: Graph, g2: Graph):
619627
for (t1, t2) in zip(sorted(_squash_graph(g1)), sorted(_squash_graph(g2))):
620628
yield t1, t2
621629

622630

623-
def _squash_graph(graph):
631+
def _squash_graph(graph: Graph):
624632
return (_squash_bnodes(triple) for triple in graph)
625633

626634

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)