Skip to content

Commit

Permalink
Python's 3.9 compatible typing annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
hgrecco committed May 14, 2023
1 parent aaac228 commit 499cce4
Show file tree
Hide file tree
Showing 26 changed files with 167 additions and 136 deletions.
4 changes: 2 additions & 2 deletions pint/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
if HAS_NUMPY:
from .compat import np

Scalar = Union[float, int, Decimal, Fraction, np.number[Any]]
Scalar: TypeAlias = Union[float, int, Decimal, Fraction, np.number[Any]]
Array = np.ndarray[Any, Any]
else:
Scalar = Union[float, int, Decimal, Fraction]
Scalar: TypeAlias = Union[float, int, Decimal, Fraction]
Array: TypeAlias = Never

# TODO: Change when Python 3.10 becomes minimal version.
Expand Down
12 changes: 6 additions & 6 deletions pint/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from io import BytesIO
from numbers import Number
from collections.abc import Mapping
from typing import Any, NoReturn, Callable
from typing import Any, NoReturn, Callable, Optional, Union
from collections.abc import Generator, Iterable


Expand All @@ -41,7 +41,7 @@


def missing_dependency(
package: str, display_name: str | None = None
package: str, display_name: Optional[str] = None
) -> Callable[..., NoReturn]:
"""Return a helper function that raises an exception when used.
Expand Down Expand Up @@ -225,7 +225,7 @@ def _to_magnitude(value, force_ndarray=False, force_ndarray_like=False):
)

#: Map type name to the actual type (for upcast types).
upcast_type_map: Mapping[str, type | None] = {k: None for k in upcast_type_names}
upcast_type_map: Mapping[str, Optional[type]] = {k: None for k in upcast_type_names}


def fully_qualified_name(t: type) -> str:
Expand Down Expand Up @@ -286,7 +286,7 @@ def is_duck_array(obj: type) -> bool:
return is_duck_array_type(type(obj))


def eq(lhs: Any, rhs: Any, check_all: bool) -> bool | Iterable[bool]:
def eq(lhs: Any, rhs: Any, check_all: bool) -> Union[bool, Iterable[bool]]:
"""Comparison of scalars and arrays.
Parameters
Expand All @@ -309,7 +309,7 @@ def eq(lhs: Any, rhs: Any, check_all: bool) -> bool | Iterable[bool]:
return out


def isnan(obj: Any, check_all: bool) -> bool | Iterable[bool]:
def isnan(obj: Any, check_all: bool) -> Union[bool, Iterable[bool]]:
"""Test for NaN or NaT.
Parameters
Expand Down Expand Up @@ -342,7 +342,7 @@ def isnan(obj: Any, check_all: bool) -> bool | Iterable[bool]:
return False


def zero_or_nan(obj: Any, check_all: bool) -> bool | Iterable[bool]:
def zero_or_nan(obj: Any, check_all: bool) -> Union[bool, Iterable[bool]]:
"""Test if obj is zero, NaN, or NaT.
Parameters
Expand Down
4 changes: 2 additions & 2 deletions pint/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from dataclasses import dataclass
from dataclasses import fields as dc_fields

from typing import Any
from typing import Any, Optional

from ._typing import Magnitude

Expand Down Expand Up @@ -53,7 +53,7 @@ def get_field_names(cls, new_cls: type) -> frozenset[str]:
return frozenset(p.name for p in dc_fields(new_cls))

@classmethod
def preprocess_kwargs(cls, **kwargs: Any) -> dict[str, Any] | None:
def preprocess_kwargs(cls, **kwargs: Any) -> Optional[dict[str, Any]]:
return None

@classmethod
Expand Down
7 changes: 4 additions & 3 deletions pint/delegates/txt_defparser/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import numbers
import re
import typing as ty
from typing import Optional, Union
from dataclasses import dataclass

from ..._vendor import flexparser as fp
Expand All @@ -27,12 +28,12 @@
from . import block, common, plain

# TODO check syntax
T = ty.TypeVar("T", bound="ForwardRelation | BidirectionalRelation")
T = ty.TypeVar("T", bound="Union[ForwardRelation, BidirectionalRelation]")


def _from_string_and_context_sep(
cls: type[T], s: str, config: ParserConfig, separator: str
) -> T | None:
) -> Optional[T]:
if separator not in s:
return None
if ":" not in s:
Expand Down Expand Up @@ -199,7 +200,7 @@ def defaults(self) -> dict[str, numbers.Number]:
return self.opening.defaults

@property
def relations(self) -> tuple[BidirectionalRelation | ForwardRelation, ...]:
def relations(self) -> tuple[Union[BidirectionalRelation, ForwardRelation], ...]:
return tuple(
r
for r in self.body
Expand Down
7 changes: 5 additions & 2 deletions pint/delegates/txt_defparser/defparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pathlib
import typing as ty
from typing import Optional, Union

from ..._vendor import flexcache as fc
from ..._vendor import flexparser as fp
Expand Down Expand Up @@ -130,15 +131,17 @@ def iter_parsed_project(self, parsed_project: fp.ParsedProject):
else:
yield stmt

def parse_file(self, filename: pathlib.Path | str, cfg: ParserConfig | None = None):
def parse_file(
self, filename: Union[pathlib.Path, str], cfg: Optional[ParserConfig] = None
):
return fp.parse(
filename,
_PintParser,
cfg or self._default_config,
diskcache=self._diskcache,
)

def parse_string(self, content: str, cfg: ParserConfig | None = None):
def parse_string(self, content: str, cfg: Optional[ParserConfig] = None):
return fp.parse_bytes(
content.encode("utf-8"),
_PintParser,
Expand Down
3 changes: 2 additions & 1 deletion pint/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import annotations

from typing import Union
import typing as ty
from dataclasses import dataclass, fields

Expand Down Expand Up @@ -134,7 +135,7 @@ def __reduce__(self):
class UndefinedUnitError(AttributeError, PintError):
"""Raised when the units are not defined in the unit registry."""

unit_names: str | tuple[str, ...]
unit_names: Union[str, tuple[str, ...]]

def __str__(self):
if isinstance(self.unit_names, str):
Expand Down
18 changes: 9 additions & 9 deletions pint/facets/context/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import weakref
from collections import ChainMap, defaultdict
from typing import Any, Callable, Protocol, Generic
from typing import Any, Callable, Protocol, Generic, Optional
from collections.abc import Iterable

from ...facets.plain import UnitDefinition, PlainQuantity, PlainUnit, MagnitudeT
Expand Down Expand Up @@ -91,11 +91,11 @@ class Context:

def __init__(
self,
name: str | None = None,
name: Optional[str] = None,
aliases: tuple[str, ...] = tuple(),
defaults: dict[str, Any] | None = None,
defaults: Optional[dict[str, Any]] = None,
) -> None:
self.name: str | None = name
self.name: Optional[str] = name
self.aliases: tuple[str, ...] = aliases

#: Maps (src, dst) -> transformation function
Expand Down Expand Up @@ -150,7 +150,7 @@ def from_context(cls, context: Context, **defaults: Any) -> Context:
def from_lines(
cls,
lines: Iterable[str],
to_base_func: ToBaseFunc | None = None,
to_base_func: Optional[ToBaseFunc] = None,
non_int_type: type = float,
) -> Context:
context_definition = ContextDefinition.from_lines(lines, non_int_type)
Expand All @@ -162,7 +162,7 @@ def from_lines(

@classmethod
def from_definition(
cls, cd: ContextDefinition, to_base_func: ToBaseFunc | None = None
cls, cd: ContextDefinition, to_base_func: Optional[ToBaseFunc] = None
) -> Context:
ctx = cls(cd.name, cd.aliases, cd.defaults)

Expand Down Expand Up @@ -241,7 +241,7 @@ def _redefine(self, definition: UnitDefinition):
def hashable(
self,
) -> tuple[
str | None,
Optional[str],
tuple[str, ...],
frozenset[tuple[SrcDst, int]],
frozenset[tuple[str, Any]],
Expand Down Expand Up @@ -273,7 +273,7 @@ def __init__(self):
super().__init__()
self.contexts: list[Context] = []
self.maps.clear() # Remove default empty map
self._graph: dict[SrcDst, set[UnitsContainer]] | None = None
self._graph: Optional[dict[SrcDst, set[UnitsContainer]]] = None

def insert_contexts(self, *contexts: Context):
"""Insert one or more contexts in reversed order the chained map.
Expand All @@ -287,7 +287,7 @@ def insert_contexts(self, *contexts: Context):
self.maps = [ctx.relation_to_context for ctx in reversed(contexts)] + self.maps
self._graph = None

def remove_contexts(self, n: int | None = None):
def remove_contexts(self, n: Optional[int] = None):
"""Remove the last n inserted contexts from the chain.
Parameters
Expand Down
10 changes: 5 additions & 5 deletions pint/facets/context/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import functools
from collections import ChainMap
from contextlib import contextmanager
from typing import Any, Callable, Generator, Generic
from typing import Any, Callable, Generator, Generic, Optional, Union

from ...compat import TypeAlias
from ..._typing import F, Magnitude
Expand Down Expand Up @@ -74,7 +74,7 @@ def _register_definition_adders(self) -> None:
super()._register_definition_adders()
self._register_adder(ContextDefinition, self.add_context)

def add_context(self, context: objects.Context | ContextDefinition) -> None:
def add_context(self, context: Union[objects.Context, ContextDefinition]) -> None:
"""Add a context object to the registry.
The context will be accessible by its name and aliases.
Expand Down Expand Up @@ -197,7 +197,7 @@ def _redefine(self, definition: UnitDefinition) -> None:
self.define(definition)

def enable_contexts(
self, *names_or_contexts: str | objects.Context, **kwargs: Any
self, *names_or_contexts: Union[str, objects.Context], **kwargs: Any
) -> None:
"""Enable contexts provided by name or by object.
Expand Down Expand Up @@ -244,7 +244,7 @@ def enable_contexts(
self._active_ctx.insert_contexts(*contexts)
self._switch_context_cache_and_units()

def disable_contexts(self, n: int | None = None) -> None:
def disable_contexts(self, n: Optional[int] = None) -> None:
"""Disable the last n enabled contexts.
Parameters
Expand Down Expand Up @@ -403,7 +403,7 @@ def _convert(
return super()._convert(value, src, dst, inplace)

def _get_compatible_units(
self, input_units: UnitsContainer, group_or_system: str | None = None
self, input_units: UnitsContainer, group_or_system: Optional[str] = None
):
src_dim = self._get_dimensionality(input_units)

Expand Down
3 changes: 2 additions & 1 deletion pint/facets/group/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from collections.abc import Iterable
from dataclasses import dataclass
from typing import Optional

from ...compat import Self
from ... import errors
Expand All @@ -30,7 +31,7 @@ class GroupDefinition(errors.WithDefErr):
@classmethod
def from_lines(
cls: type[Self], lines: Iterable[str], non_int_type: type
) -> Self | None:
) -> Optional[Self]:
# TODO: this is to keep it backwards compatible
from ...delegates import ParserConfig, txt_defparser

Expand Down
8 changes: 5 additions & 3 deletions pint/facets/group/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from __future__ import annotations

from typing import Callable, Any, TYPE_CHECKING, Generic
from typing import Callable, Any, TYPE_CHECKING, Generic, Optional

from collections.abc import Generator, Iterable
from ...util import SharedRegistryObject, getattr_maybe_raise
Expand Down Expand Up @@ -81,7 +81,7 @@ def __init__(self, name: str):

#: A cache of the included units.
#: None indicates that the cache has been invalidated.
self._computed_members: frozenset[str] | None = None
self._computed_members: Optional[frozenset[str]] = None

@property
def members(self) -> frozenset[str]:
Expand Down Expand Up @@ -195,7 +195,9 @@ def from_lines(

@classmethod
def from_definition(
cls, group_definition: GroupDefinition, add_unit_func: AddUnitFunc | None = None
cls,
group_definition: GroupDefinition,
add_unit_func: Optional[AddUnitFunc] = None,
) -> Group:
grp = cls(group_definition.name)

Expand Down
7 changes: 3 additions & 4 deletions pint/facets/group/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Generic, Any
from typing import TYPE_CHECKING, Generic, Any, Optional

from ...compat import TypeAlias
from ... import errors
Expand Down Expand Up @@ -47,7 +47,6 @@ class GenericGroupRegistry(
def __init__(self, **kwargs):
super().__init__(**kwargs)
#: Map group name to group.
#: :type: dict[ str | Group]
self._groups: dict[str, objects.Group] = {}
self._groups["root"] = self.Group("root")

Expand Down Expand Up @@ -122,7 +121,7 @@ def get_group(self, name: str, create_if_needed: bool = True) -> objects.Group:
return self.Group(name)

def get_compatible_units(
self, input_units: UnitsContainer, group: str | None = None
self, input_units: UnitsContainer, group: Optional[str] = None
) -> frozenset[Unit]:
""" """
if group is None:
Expand All @@ -135,7 +134,7 @@ def get_compatible_units(
return frozenset(self.Unit(eq) for eq in equiv)

def _get_compatible_units(
self, input_units: UnitsContainer, group: str | None = None
self, input_units: UnitsContainer, group: Optional[str] = None
) -> frozenset[str]:
ret = super()._get_compatible_units(input_units)

Expand Down
4 changes: 2 additions & 2 deletions pint/facets/nonmultiplicative/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from __future__ import annotations

from typing import Generic
from typing import Generic, Optional

from ..plain import PlainQuantity, PlainUnit, MagnitudeT

Expand Down Expand Up @@ -42,7 +42,7 @@ def _has_compatible_delta(self, unit: str) -> bool:
self._get_unit_definition(d).reference == offset_unit_dim for d in deltas
)

def _ok_for_muldiv(self, no_offset_units: int | None = None) -> bool:
def _ok_for_muldiv(self, no_offset_units: Optional[int] = None) -> bool:
"""Checks if PlainQuantity object can be multiplied or divided"""

is_ok = True
Expand Down
Loading

0 comments on commit 499cce4

Please sign in to comment.