Skip to content

Commit

Permalink
chore: type annotations - convert uses of Optional and some Union usa…
Browse files Browse the repository at this point in the history
…ge to union operator | (#2971)

* chore: type annotations update checkpoint.

some w3c sparql10 tests now passing, but not sure how

* chore: type annotations - refactor usage of typing.Optional
  • Loading branch information
edmondchuc authored Nov 6, 2024
1 parent d73f50c commit ac0566f
Show file tree
Hide file tree
Showing 106 changed files with 1,093 additions and 1,101 deletions.
4 changes: 2 additions & 2 deletions examples/secure_with_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import logging
import os
import sys
from typing import Any, Optional
from typing import Any

from rdflib import Graph

Expand Down Expand Up @@ -70,7 +70,7 @@ def main() -> None:

# Attempt to parse a JSON-LD document that will result in the blocked URL
# being accessed.
error: Optional[PermissionError] = None
error: PermissionError | None = None
try:
graph.parse(
data=r"""{
Expand Down
3 changes: 1 addition & 2 deletions examples/secure_with_urlopen.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import logging
import os
import sys
from typing import Optional
from urllib.request import HTTPHandler, OpenerDirector, Request, install_opener

from rdflib import Graph
Expand Down Expand Up @@ -61,7 +60,7 @@ def main() -> None:

# Attempt to parse a JSON-LD document that will result in the blocked URL
# being accessed.
error: Optional[PermissionError] = None
error: PermissionError | None = None
try:
graph.parse(
data=r"""{
Expand Down
6 changes: 3 additions & 3 deletions rdflib/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,11 @@ def n3(self) -> str:
"""
return "( %s )" % (" ".join([i.n3() for i in self]))

def _get_container(self, index: int) -> Optional[IdentifiedNode]:
def _get_container(self, index: int) -> IdentifiedNode | None:
"""Gets the first, rest holding node at index."""
assert isinstance(index, int)
graph = self.graph
container: Optional[IdentifiedNode] = self.uri
container: IdentifiedNode | None = self.uri
i = 0
while i < index and container is not None:
i += 1
Expand Down Expand Up @@ -274,7 +274,7 @@ def __iadd__(self, other: Iterable[_ObjectType]):
return self

def clear(self):
container: Optional[IdentifiedNode] = self.uri
container: IdentifiedNode | None = self.uri
graph = self.graph
while container is not None:
rest = graph.value(container, RDF.rest)
Expand Down
14 changes: 6 additions & 8 deletions rdflib/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def __str__(self):
def key(self):
return (len(self.nodes), self.hash_color())

def hash_color(self, color: Optional[tuple[ColorItem, ...]] = None) -> str:
def hash_color(self, color: tuple[ColorItem, ...] | None = None) -> str:
if color is None:
color = self.color
if color in self._hash_cache:
Expand Down Expand Up @@ -371,7 +371,7 @@ def _refine(self, coloring: list[Color], sequence: list[Color]) -> list[Color]:
return combined_colors

@_runtime("to_hash_runtime")
def to_hash(self, stats: Optional[Stats] = None):
def to_hash(self, stats: Stats | None = None):
result = 0
for triple in self.canonical_triples(stats=stats):
result += self.hashfunc(" ".join([x.n3() for x in triple]))
Expand All @@ -392,7 +392,7 @@ def _experimental_path(self, coloring: list[Color]) -> list[Color]:
def _create_generator(
self,
colorings: list[list[Color]],
groupings: Optional[dict[Node, set[Node]]] = None,
groupings: dict[Node, set[Node]] | None = None,
) -> dict[Node, set[Node]]:
if not groupings:
groupings = defaultdict(set)
Expand All @@ -408,7 +408,7 @@ def _create_generator(
def _traces(
self,
coloring: list[Color],
stats: Optional[Stats] = None,
stats: Stats | None = None,
depth: list[int] = [0],
) -> list[Color]:
if stats is not None and "prunings" not in stats:
Expand Down Expand Up @@ -475,7 +475,7 @@ def _traces(
depth[0] = best_depth # type: ignore[assignment]
return discrete[0]

def canonical_triples(self, stats: Optional[Stats] = None):
def canonical_triples(self, stats: Stats | None = None):
if stats is not None:
start_coloring = datetime.now()
coloring = self._initial_color()
Expand Down Expand Up @@ -569,9 +569,7 @@ def isomorphic(graph1: Graph, graph2: Graph) -> bool:
return gd1 == gd2


def to_canonical_graph(
g1: Graph, stats: Optional[Stats] = None
) -> ReadOnlyGraphAggregate:
def to_canonical_graph(g1: Graph, stats: Stats | None = None) -> ReadOnlyGraphAggregate:
"""Creates a canonical, read-only graph.
Creates a canonical, read-only graph where all bnode id:s are based on
Expand Down
4 changes: 2 additions & 2 deletions rdflib/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

from __future__ import annotations

from typing import Any, Optional
from typing import Any

__all__ = ["Event", "Dispatcher"]

Expand Down Expand Up @@ -57,7 +57,7 @@ class Dispatcher:
subscribers.
"""

_dispatch_map: Optional[dict[Any, Any]] = None
_dispatch_map: dict[Any, Any] | None = None

def set_map(self, amap: dict[Any, Any]):
self._dispatch_map = amap
Expand Down
4 changes: 2 additions & 2 deletions rdflib/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
]


from typing import Any, Optional
from typing import Any


class Error(Exception):
"""Base class for rdflib exceptions."""

def __init__(self, msg: Optional[str] = None):
def __init__(self, msg: str | None = None):
Exception.__init__(self, msg)
self.msg = msg

Expand Down
46 changes: 23 additions & 23 deletions rdflib/extras/infixowl.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@

import itertools
import logging
from typing import TYPE_CHECKING, Optional, Union, cast
from typing import TYPE_CHECKING, Union, cast

from rdflib.collection import Collection
from rdflib.graph import Graph, _ObjectType
Expand Down Expand Up @@ -380,13 +380,13 @@ class Individual:
# Instance typing
graph: Graph
__identifier: IdentifiedNode
qname: Optional[str]
qname: str | None

def serialize(self, graph):
for fact in self.factoryGraph.triples((self.identifier, None, None)):
graph.add(fact)

def __init__(self, identifier: Optional[IdentifiedNode] = None, graph=None):
def __init__(self, identifier: IdentifiedNode | None = None, graph=None):
self.__identifier = identifier is not None and identifier or BNode()
if graph is None:
self.graph = self.factoryGraph
Expand Down Expand Up @@ -605,7 +605,7 @@ class AnnotatableTerms(Individual):

def __init__(
self,
identifier: Optional[IdentifiedNode],
identifier: IdentifiedNode | None,
graph=None,
nameAnnotation=None, # noqa: N803
nameIsLabel=False, # noqa: N803
Expand Down Expand Up @@ -663,7 +663,7 @@ def _get_comment(self):

def _set_comment(
self,
comment: Optional[IdentifiedNode | Literal | list[IdentifiedNode | Literal]],
comment: IdentifiedNode | Literal | list[IdentifiedNode | Literal] | None,
):
if not comment:
return
Expand Down Expand Up @@ -702,7 +702,7 @@ def _get_label(self):
yield label

def _set_label(
self, label: Optional[IdentifiedNode | Literal | list[IdentifiedNode | Literal]]
self, label: IdentifiedNode | Literal | list[IdentifiedNode | Literal] | None
):
if not label:
return
Expand Down Expand Up @@ -1058,7 +1058,7 @@ def setupNounAnnotations(self, noun_annotations): # noqa: N802

def __init__(
self,
identifier: Optional[IdentifiedNode] = None,
identifier: IdentifiedNode | None = None,
subClassOf=None, # noqa: N803
equivalentClass=None, # noqa: N803
disjointWith=None, # noqa: N803
Expand Down Expand Up @@ -1762,22 +1762,22 @@ class Restriction(Class):
def __init__(
self,
onProperty, # noqa: N803
graph: Optional[Graph] = None,
allValuesFrom: Optional[ # noqa: N803
IdentifiedNode | Literal | Class | bool
] = None,
someValuesFrom: Optional[ # noqa: N803
IdentifiedNode | Literal | Class | bool
] = None,
value: Optional[IdentifiedNode | Literal | Class | bool] = None,
cardinality: Optional[IdentifiedNode | Literal | Class | bool] = None,
maxCardinality: Optional[ # noqa: N803
IdentifiedNode | Literal | Class | bool
] = None,
minCardinality: Optional[ # noqa: N803
IdentifiedNode | Literal | Class | bool
] = None,
identifier: Optional[IdentifiedNode] = None,
graph: Graph | None = None,
allValuesFrom: ( # noqa: N803
IdentifiedNode | Literal | Class | bool | None
) = None,
someValuesFrom: ( # noqa: N803
IdentifiedNode | Literal | Class | bool | None
) = None,
value: IdentifiedNode | Literal | Class | bool | None = None,
cardinality: IdentifiedNode | Literal | Class | bool | None = None,
maxCardinality: ( # noqa: N803
IdentifiedNode | Literal | Class | bool | None
) = None,
minCardinality: ( # noqa: N803
IdentifiedNode | Literal | Class | bool | None
) = None,
identifier: IdentifiedNode | None = None,
):
graph = Graph() if graph is None else graph
super(Restriction, self).__init__(
Expand Down
4 changes: 2 additions & 2 deletions rdflib/extras/shacl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING

from rdflib import Graph, Literal, URIRef, paths
from rdflib.namespace import RDF, SH
Expand Down Expand Up @@ -33,7 +33,7 @@ def parse_shacl_path(
:param path_identifier: A :class:`~rdflib.term.Node` of the path
:return: A :class:`~rdflib.term.URIRef` or a :class:`~rdflib.paths.Path`
"""
path: Optional[URIRef | Path] = None
path: URIRef | Path | None = None

# Literals are not allowed.
if isinstance(path_identifier, Literal):
Expand Down
Loading

0 comments on commit ac0566f

Please sign in to comment.