summaryrefslogtreecommitdiff
path: root/pint/facets
diff options
context:
space:
mode:
Diffstat (limited to 'pint/facets')
-rw-r--r--pint/facets/context/definitions.py14
-rw-r--r--pint/facets/context/objects.py11
-rw-r--r--pint/facets/context/registry.py10
-rw-r--r--pint/facets/formatting/objects.py16
-rw-r--r--pint/facets/group/registry.py6
-rw-r--r--pint/facets/measurement/objects.py6
-rw-r--r--pint/facets/nonmultiplicative/objects.py6
-rw-r--r--pint/facets/nonmultiplicative/registry.py6
-rw-r--r--pint/facets/numpy/numpy_func.py6
-rw-r--r--pint/facets/numpy/quantity.py4
-rw-r--r--pint/facets/numpy/unit.py4
-rw-r--r--pint/facets/plain/definitions.py4
-rw-r--r--pint/facets/plain/quantity.py51
-rw-r--r--pint/facets/plain/registry.py100
-rw-r--r--pint/facets/plain/unit.py10
-rw-r--r--pint/facets/system/registry.py14
16 files changed, 121 insertions, 147 deletions
diff --git a/pint/facets/context/definitions.py b/pint/facets/context/definitions.py
index fbdb390..d9ba473 100644
--- a/pint/facets/context/definitions.py
+++ b/pint/facets/context/definitions.py
@@ -12,7 +12,7 @@ import itertools
import numbers
import re
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Callable, Dict, Set, Tuple
+from typing import TYPE_CHECKING, Any, Callable
from ... import errors
from ..plain import UnitDefinition
@@ -41,7 +41,7 @@ class Relation:
# could be used.
@property
- def variables(self) -> Set[str, ...]:
+ def variables(self) -> set[str, ...]:
"""Find all variables names in the equation."""
return set(self._varname_re.findall(self.equation))
@@ -92,13 +92,13 @@ class ContextDefinition(errors.WithDefErr):
#: name of the context
name: str
#: other na
- aliases: Tuple[str, ...]
- defaults: Dict[str, numbers.Number]
- relations: Tuple[Relation, ...]
- redefinitions: Tuple[UnitDefinition, ...]
+ aliases: tuple[str, ...]
+ defaults: dict[str, numbers.Number]
+ relations: tuple[Relation, ...]
+ redefinitions: tuple[UnitDefinition, ...]
@property
- def variables(self) -> Set[str, ...]:
+ def variables(self) -> set[str, ...]:
"""Return all variable names in all transformations."""
return set().union(*(r.variables for r in self.relations))
diff --git a/pint/facets/context/objects.py b/pint/facets/context/objects.py
index 40c2bb5..58f8bb8 100644
--- a/pint/facets/context/objects.py
+++ b/pint/facets/context/objects.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import weakref
from collections import ChainMap, defaultdict
-from typing import Optional, Tuple
from ...facets.plain import UnitDefinition
from ...util import UnitsContainer, to_units_container
@@ -70,9 +69,9 @@ class Context:
def __init__(
self,
- name: Optional[str] = None,
- aliases: Tuple[str, ...] = (),
- defaults: Optional[dict] = None,
+ name: str | None = None,
+ aliases: tuple[str, ...] = (),
+ defaults: dict | None = None,
) -> None:
self.name = name
self.aliases = aliases
@@ -166,7 +165,7 @@ class Context:
del self.relation_to_context[_key]
@staticmethod
- def __keytransform__(src, dst) -> Tuple[UnitsContainer, UnitsContainer]:
+ def __keytransform__(src, dst) -> tuple[UnitsContainer, UnitsContainer]:
return to_units_container(src), to_units_container(dst)
def transform(self, src, dst, registry, value):
@@ -199,7 +198,7 @@ class Context:
def hashable(
self,
- ) -> Tuple[Optional[str], Tuple[str, ...], frozenset, frozenset, tuple]:
+ ) -> tuple[str | None, tuple[str, ...], frozenset, frozenset, tuple]:
"""Generate a unique hashable and comparable representation of self, which can
be used as a key in a dict. This class cannot define ``__hash__`` because it is
mutable, and the Python interpreter does cache the output of ``__hash__``.
diff --git a/pint/facets/context/registry.py b/pint/facets/context/registry.py
index ccf69d2..108bdf0 100644
--- a/pint/facets/context/registry.py
+++ b/pint/facets/context/registry.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import functools
from collections import ChainMap
from contextlib import contextmanager
-from typing import Any, Callable, ContextManager, Dict, Union
+from typing import Any, Callable, ContextManager
from ..._typing import F
from ...errors import UndefinedUnitError
@@ -54,7 +54,7 @@ class ContextRegistry(PlainRegistry):
def __init__(self, **kwargs: Any) -> None:
# Map context name (string) or abbreviation to context.
- self._contexts: Dict[str, Context] = {}
+ self._contexts: dict[str, Context] = {}
# Stores active contexts.
self._active_ctx = ContextChain()
# Map context chain to cache
@@ -71,7 +71,7 @@ class ContextRegistry(PlainRegistry):
super()._register_definition_adders()
self._register_adder(ContextDefinition, self.add_context)
- def add_context(self, context: Union[Context, ContextDefinition]) -> None:
+ def add_context(self, context: Context | ContextDefinition) -> None:
"""Add a context object to the registry.
The context will be accessible by its name and aliases.
@@ -193,9 +193,7 @@ class ContextRegistry(PlainRegistry):
# Write into the context-specific self._units.maps[0] and self._cache.root_units
self.define(definition)
- def enable_contexts(
- self, *names_or_contexts: Union[str, Context], **kwargs
- ) -> None:
+ def enable_contexts(self, *names_or_contexts: str | Context, **kwargs) -> None:
"""Enable contexts provided by name or by object.
Parameters
diff --git a/pint/facets/formatting/objects.py b/pint/facets/formatting/objects.py
index 1ba92c9..212fcb5 100644
--- a/pint/facets/formatting/objects.py
+++ b/pint/facets/formatting/objects.py
@@ -80,7 +80,7 @@ class FormattingQuantity:
else:
if isinstance(self.magnitude, ndarray):
# Use custom ndarray text formatting with monospace font
- formatter = "{{:{}}}".format(mspec)
+ formatter = f"{{:{mspec}}}"
# Need to override for scalars, which are detected as iterable,
# and don't respond to printoptions.
if self.magnitude.ndim == 0:
@@ -112,7 +112,7 @@ class FormattingQuantity:
else:
# Use custom ndarray text formatting--need to handle scalars differently
# since they don't respond to printoptions
- formatter = "{{:{}}}".format(mspec)
+ formatter = f"{{:{mspec}}}"
if obj.magnitude.ndim == 0:
mstr = formatter.format(obj.magnitude)
else:
@@ -188,10 +188,10 @@ class FormattingUnit:
if not self._units:
return ""
units = UnitsContainer(
- dict(
- (self._REGISTRY._get_symbol(key), value)
+ {
+ self._REGISTRY._get_symbol(key): value
for key, value in self._units.items()
- )
+ }
)
uspec = uspec.replace("~", "")
else:
@@ -206,10 +206,10 @@ class FormattingUnit:
if self.dimensionless:
return ""
units = UnitsContainer(
- dict(
- (self._REGISTRY._get_symbol(key), value)
+ {
+ self._REGISTRY._get_symbol(key): value
for key, value in self._units.items()
- )
+ }
)
spec = spec.replace("~", "")
else:
diff --git a/pint/facets/group/registry.py b/pint/facets/group/registry.py
index 7269082..c6cc06d 100644
--- a/pint/facets/group/registry.py
+++ b/pint/facets/group/registry.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Dict, FrozenSet
+from typing import TYPE_CHECKING
from ... import errors
@@ -40,7 +40,7 @@ class GroupRegistry(PlainRegistry):
super().__init__(**kwargs)
#: Map group name to group.
#: :type: dict[ str | Group]
- self._groups: Dict[str, Group] = {}
+ self._groups: dict[str, Group] = {}
self._groups["root"] = self.Group("root")
def __init_subclass__(cls, **kwargs):
@@ -117,7 +117,7 @@ class GroupRegistry(PlainRegistry):
return self.Group(name)
- def _get_compatible_units(self, input_units, group) -> FrozenSet["Unit"]:
+ def _get_compatible_units(self, input_units, group) -> frozenset[Unit]:
ret = super()._get_compatible_units(input_units, group)
if not group:
diff --git a/pint/facets/measurement/objects.py b/pint/facets/measurement/objects.py
index 0fed93f..6fa860c 100644
--- a/pint/facets/measurement/objects.py
+++ b/pint/facets/measurement/objects.py
@@ -23,7 +23,7 @@ class MeasurementQuantity:
def plus_minus(self, error, relative=False):
if isinstance(error, self.__class__):
if relative:
- raise ValueError("{} is not a valid relative error.".format(error))
+ raise ValueError(f"{error} is not a valid relative error.")
error = error.to(self._units).magnitude
else:
if relative:
@@ -98,7 +98,7 @@ class Measurement(PlainQuantity):
)
def __str__(self):
- return "{}".format(self)
+ return f"{self}"
def __format__(self, spec):
spec = spec or self.default_format
@@ -133,7 +133,7 @@ class Measurement(PlainQuantity):
# scientific notation ('e' or 'E' and sometimes 'g' or 'G').
mstr = mstr.replace("(", "").replace(")", " ")
ustr = siunitx_format_unit(self.units._units, self._REGISTRY)
- return r"\SI%s{%s}{%s}" % (opts, mstr, ustr)
+ return r"\SI{}{{{}}}{{{}}}".format(opts, mstr, ustr)
# standard cases
if "L" in spec:
diff --git a/pint/facets/nonmultiplicative/objects.py b/pint/facets/nonmultiplicative/objects.py
index 1708e32..a0456de 100644
--- a/pint/facets/nonmultiplicative/objects.py
+++ b/pint/facets/nonmultiplicative/objects.py
@@ -8,8 +8,6 @@
from __future__ import annotations
-from typing import List
-
class NonMultiplicativeQuantity:
@property
@@ -17,7 +15,7 @@ class NonMultiplicativeQuantity:
"""Check if the PlainQuantity object has only multiplicative units."""
return not self._get_non_multiplicative_units()
- def _get_non_multiplicative_units(self) -> List[str]:
+ def _get_non_multiplicative_units(self) -> list[str]:
"""Return a list of the of non-multiplicative units of the PlainQuantity object."""
return [
unit
@@ -25,7 +23,7 @@ class NonMultiplicativeQuantity:
if not self._get_unit_definition(unit).is_multiplicative
]
- def _get_delta_units(self) -> List[str]:
+ def _get_delta_units(self) -> list[str]:
"""Return list of delta units ot the PlainQuantity object."""
return [u for u in self._units if u.startswith("delta_")]
diff --git a/pint/facets/nonmultiplicative/registry.py b/pint/facets/nonmultiplicative/registry.py
index 17b053e..9bbc1aa 100644
--- a/pint/facets/nonmultiplicative/registry.py
+++ b/pint/facets/nonmultiplicative/registry.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any
from ...errors import DimensionalityError, UndefinedUnitError
from ...util import UnitsContainer, logger
@@ -56,8 +56,8 @@ class NonMultiplicativeRegistry(PlainRegistry):
def _parse_units(
self,
input_string: str,
- as_delta: Optional[bool] = None,
- case_sensitive: Optional[bool] = None,
+ as_delta: bool | None = None,
+ case_sensitive: bool | None = None,
):
""" """
if as_delta is None:
diff --git a/pint/facets/numpy/numpy_func.py b/pint/facets/numpy/numpy_func.py
index f25f4a4..0688367 100644
--- a/pint/facets/numpy/numpy_func.py
+++ b/pint/facets/numpy/numpy_func.py
@@ -220,7 +220,7 @@ def get_op_output_unit(unit_op, first_input_units, all_args=None, size=None):
product /= x.units
result_unit = product**-1
else:
- raise ValueError("Output unit method {} not understood".format(unit_op))
+ raise ValueError(f"Output unit method {unit_op} not understood")
return result_unit
@@ -237,7 +237,7 @@ def implements(numpy_func_string, func_type):
elif func_type == "ufunc":
HANDLED_UFUNCS[numpy_func_string] = func
else:
- raise ValueError("Invalid func_type {}".format(func_type))
+ raise ValueError(f"Invalid func_type {func_type}")
return func
return decorator
@@ -997,7 +997,7 @@ def numpy_wrap(func_type, func, args, kwargs, types):
# ufuncs do not have func.__module__
name = func.__name__
else:
- raise ValueError("Invalid func_type {}".format(func_type))
+ raise ValueError(f"Invalid func_type {func_type}")
if name not in handled or any(is_upcast_type(t) for t in types):
return NotImplemented
diff --git a/pint/facets/numpy/quantity.py b/pint/facets/numpy/quantity.py
index 9aa55ce..f9c1d86 100644
--- a/pint/facets/numpy/quantity.py
+++ b/pint/facets/numpy/quantity.py
@@ -52,11 +52,11 @@ class NumpyQuantity:
return NotImplemented
# Replicate types from __array_function__
- types = set(
+ types = {
type(arg)
for arg in list(inputs) + list(kwargs.values())
if hasattr(arg, "__array_ufunc__")
- )
+ }
return numpy_wrap("ufunc", ufunc, inputs, kwargs, types)
diff --git a/pint/facets/numpy/unit.py b/pint/facets/numpy/unit.py
index 0b5007f..73df59f 100644
--- a/pint/facets/numpy/unit.py
+++ b/pint/facets/numpy/unit.py
@@ -20,11 +20,11 @@ class NumpyUnit:
return NotImplemented
# Check types and return NotImplemented when upcast type encountered
- types = set(
+ types = {
type(arg)
for arg in list(inputs) + list(kwargs.values())
if hasattr(arg, "__array_ufunc__")
- )
+ }
if any(is_upcast_type(other) for other in types):
return NotImplemented
diff --git a/pint/facets/plain/definitions.py b/pint/facets/plain/definitions.py
index 11a3095..eb45db1 100644
--- a/pint/facets/plain/definitions.py
+++ b/pint/facets/plain/definitions.py
@@ -13,7 +13,7 @@ import numbers
import typing as ty
from dataclasses import dataclass
from functools import cached_property
-from typing import Callable, Optional
+from typing import Callable
from ... import errors
from ...converters import Converter
@@ -76,7 +76,7 @@ class PrefixDefinition(errors.WithDefErr):
#: scaling value for this prefix
value: numbers.Number
#: canonical symbol
- defined_symbol: Optional[str] = ""
+ defined_symbol: str | None = ""
#: additional names for the same prefix
aliases: ty.Tuple[str, ...] = ()
diff --git a/pint/facets/plain/quantity.py b/pint/facets/plain/quantity.py
index 359e613..df57ff0 100644
--- a/pint/facets/plain/quantity.py
+++ b/pint/facets/plain/quantity.py
@@ -20,18 +20,11 @@ from typing import (
TYPE_CHECKING,
Any,
Callable,
- Dict,
Generic,
- Iterable,
- Iterator,
- List,
- Optional,
- Sequence,
- Tuple,
TypeVar,
- Union,
overload,
)
+from collections.abc import Iterable, Iterator, Sequence
from ..._typing import S, UnitLike, _MagnitudeType
from ...compat import (
@@ -179,25 +172,25 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
@overload
def __new__(
- cls, value: str, units: Optional[UnitLike] = None
+ cls, value: str, units: UnitLike | None = None
) -> PlainQuantity[Magnitude]:
...
@overload
def __new__( # type: ignore[misc]
- cls, value: Sequence, units: Optional[UnitLike] = None
+ cls, value: Sequence, units: UnitLike | None = None
) -> PlainQuantity[np.ndarray]:
...
@overload
def __new__(
- cls, value: PlainQuantity[Magnitude], units: Optional[UnitLike] = None
+ cls, value: PlainQuantity[Magnitude], units: UnitLike | None = None
) -> PlainQuantity[Magnitude]:
...
@overload
def __new__(
- cls, value: Magnitude, units: Optional[UnitLike] = None
+ cls, value: Magnitude, units: UnitLike | None = None
) -> PlainQuantity[Magnitude]:
...
@@ -316,12 +309,12 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
return self.to(units).magnitude
@property
- def units(self) -> "Unit":
+ def units(self) -> Unit:
"""PlainQuantity's units. Long form for `u`"""
return self._REGISTRY.Unit(self._units)
@property
- def u(self) -> "Unit":
+ def u(self) -> Unit:
"""PlainQuantity's units. Short form for `units`"""
return self._REGISTRY.Unit(self._units)
@@ -337,7 +330,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
return not bool(tmp.dimensionality)
- _dimensionality: Optional[UnitsContainerT] = None
+ _dimensionality: UnitsContainerT | None = None
@property
def dimensionality(self) -> UnitsContainerT:
@@ -358,7 +351,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
@classmethod
def from_list(
- cls, quant_list: List[PlainQuantity], units=None
+ cls, quant_list: list[PlainQuantity], units=None
) -> PlainQuantity[np.ndarray]:
"""Transforms a list of Quantities into an numpy.array quantity.
If no units are specified, the unit of the first element will be used.
@@ -421,7 +414,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
def from_tuple(cls, tup):
return cls(tup[0], cls._REGISTRY.UnitsContainer(tup[1]))
- def to_tuple(self) -> Tuple[_MagnitudeType, Tuple[Tuple[str]]]:
+ def to_tuple(self) -> tuple[_MagnitudeType, tuple[tuple[str]]]:
return self.m, tuple(self._units.items())
def compatible_units(self, *contexts):
@@ -432,7 +425,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
return self._REGISTRY.get_compatible_units(self._units)
def is_compatible_with(
- self, other: Any, *contexts: Union[str, Context], **ctx_kwargs: Any
+ self, other: Any, *contexts: str | Context, **ctx_kwargs: Any
) -> bool:
"""check if the other object is compatible
@@ -652,7 +645,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
):
return self
- SI_prefixes: Dict[int, str] = {}
+ SI_prefixes: dict[int, str] = {}
for prefix in self._REGISTRY._prefixes.values():
try:
scale = prefix.converter.scale
@@ -702,7 +695,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
return self.to(new_unit_container)
def to_preferred(
- self, preferred_units: List[UnitLike]
+ self, preferred_units: list[UnitLike]
) -> PlainQuantity[_MagnitudeType]:
"""Return Quantity converted to a unit composed of the preferred units.
@@ -732,9 +725,9 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
for preferred_unit in preferred_units:
dims = sorted(preferred_unit.dimensionality)
if dims == self_dims:
- p_exps_head, *p_exps_tail = [
+ p_exps_head, *p_exps_tail = (
preferred_unit.dimensionality[d] for d in dims
- ]
+ )
if all(
s_exps_tail[i] * p_exps_head == p_exps_tail[i] ** s_exps_head
for i in range(n)
@@ -812,13 +805,13 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
# update preferred_units with the selected units that were originally preferred
preferred_units = list(
- set(u for d, u in unit_selections.items() if d in preferred_dims)
+ {u for d, u in unit_selections.items() if d in preferred_dims}
)
preferred_units.sort(key=lambda unit: str(unit)) # for determinism
# and unpreferred_units are the selected units that weren't originally preferred
unpreferred_units = list(
- set(u for d, u in unit_selections.items() if d not in preferred_dims)
+ {u for d, u in unit_selections.items() if d not in preferred_dims}
)
unpreferred_units.sort(key=lambda unit: str(unit)) # for determinism
@@ -1627,7 +1620,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
def __abs__(self) -> PlainQuantity[_MagnitudeType]:
return self.__class__(abs(self._magnitude), self._units)
- def __round__(self, ndigits: Optional[int] = 0) -> PlainQuantity[int]:
+ def __round__(self, ndigits: int | None = 0) -> PlainQuantity[int]:
return self.__class__(round(self._magnitude, ndigits=ndigits), self._units)
def __pos__(self) -> PlainQuantity[_MagnitudeType]:
@@ -1720,9 +1713,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
else:
raise OffsetUnitCalculusError(self._units)
else:
- raise ValueError(
- "Cannot compare PlainQuantity and {}".format(type(other))
- )
+ raise ValueError(f"Cannot compare PlainQuantity and {type(other)}")
# Registry equality check based on util.SharedRegistryObject
if self._REGISTRY is not other._REGISTRY:
@@ -1791,11 +1782,11 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType]
"""Check if the PlainQuantity object has only multiplicative units."""
return True
- def _get_non_multiplicative_units(self) -> List[str]:
+ def _get_non_multiplicative_units(self) -> list[str]:
"""Return a list of the of non-multiplicative units of the PlainQuantity object."""
return []
- def _get_delta_units(self) -> List[str]:
+ def _get_delta_units(self) -> list[str]:
"""Return list of delta units ot the PlainQuantity object."""
return [u for u in self._units if u.startswith("delta_")]
diff --git a/pint/facets/plain/registry.py b/pint/facets/plain/registry.py
index dbe755d..7eddcb5 100644
--- a/pint/facets/plain/registry.py
+++ b/pint/facets/plain/registry.py
@@ -24,18 +24,10 @@ from typing import (
TYPE_CHECKING,
Any,
Callable,
- Dict,
- FrozenSet,
- Iterable,
- Iterator,
- List,
- Optional,
- Set,
- Tuple,
- Type,
TypeVar,
Union,
)
+from collections.abc import Iterable, Iterator
if TYPE_CHECKING:
from ..context import Context
@@ -83,7 +75,7 @@ T = TypeVar("T")
_BLOCK_RE = re.compile(r"[ (]")
-@functools.lru_cache()
+@functools.lru_cache
def pattern_to_regex(pattern):
if hasattr(pattern, "finditer"):
pattern = pattern.pattern
@@ -96,7 +88,7 @@ def pattern_to_regex(pattern):
return re.compile(pattern)
-NON_INT_TYPE = Type[Union[float, Decimal, Fraction]]
+NON_INT_TYPE = type[Union[float, Decimal, Fraction]]
PreprocessorType = Callable[[str], str]
@@ -105,13 +97,13 @@ class RegistryCache:
def __init__(self) -> None:
#: Maps dimensionality (UnitsContainer) to Units (str)
- self.dimensional_equivalents: Dict[UnitsContainer, Set[str]] = {}
+ self.dimensional_equivalents: dict[UnitsContainer, set[str]] = {}
#: Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer)
self.root_units = {}
#: Maps dimensionality (UnitsContainer) to Units (UnitsContainer)
- self.dimensionality: Dict[UnitsContainer, UnitsContainer] = {}
+ self.dimensionality: dict[UnitsContainer, UnitsContainer] = {}
#: Cache the unit name associated to user input. ('mV' -> 'millivolt')
- self.parse_unit: Dict[str, UnitsContainer] = {}
+ self.parse_unit: dict[str, UnitsContainer] = {}
def __eq__(self, other):
if not isinstance(other, self.__class__):
@@ -181,7 +173,7 @@ class PlainRegistry(metaclass=RegistryMeta):
"""
#: Babel.Locale instance or None
- fmt_locale: Optional[Locale] = None
+ fmt_locale: Locale | None = None
_diskcache = None
@@ -197,12 +189,12 @@ class PlainRegistry(metaclass=RegistryMeta):
force_ndarray_like: bool = False,
on_redefinition: str = "warn",
auto_reduce_dimensions: bool = False,
- preprocessors: Optional[List[PreprocessorType]] = None,
- fmt_locale: Optional[str] = None,
+ preprocessors: list[PreprocessorType] | None = None,
+ fmt_locale: str | None = None,
non_int_type: NON_INT_TYPE = float,
case_sensitive: bool = True,
- cache_folder: Union[str, pathlib.Path, None] = None,
- separate_format_defaults: Optional[bool] = None,
+ cache_folder: str | pathlib.Path | None = None,
+ separate_format_defaults: bool | None = None,
mpl_formatter: str = "{:P}",
):
#: Map a definition class to a adder methods.
@@ -255,31 +247,31 @@ class PlainRegistry(metaclass=RegistryMeta):
#: Map between name (string) and value (string) of defaults stored in the
#: definitions file.
- self._defaults: Dict[str, str] = {}
+ self._defaults: dict[str, str] = {}
#: Map dimension name (string) to its definition (DimensionDefinition).
- self._dimensions: Dict[
- str, Union[DimensionDefinition, DerivedDimensionDefinition]
+ self._dimensions: dict[
+ str, DimensionDefinition | DerivedDimensionDefinition
] = {}
#: Map unit name (string) to its definition (UnitDefinition).
#: Might contain prefixed units.
- self._units: Dict[str, UnitDefinition] = {}
+ self._units: dict[str, UnitDefinition] = {}
#: List base unit names
- self._base_units: List[str] = []
+ self._base_units: list[str] = []
#: Map unit name in lower case (string) to a set of unit names with the right
#: case.
#: Does not contain prefixed units.
#: e.g: 'hz' - > set('Hz', )
- self._units_casei: Dict[str, Set[str]] = defaultdict(set)
+ self._units_casei: dict[str, set[str]] = defaultdict(set)
#: Map prefix name (string) to its definition (PrefixDefinition).
- self._prefixes: Dict[str, PrefixDefinition] = {"": PrefixDefinition("", 1)}
+ self._prefixes: dict[str, PrefixDefinition] = {"": PrefixDefinition("", 1)}
#: Map suffix name (string) to canonical , and unit alias to canonical unit name
- self._suffixes: Dict[str, str] = {"": "", "s": ""}
+ self._suffixes: dict[str, str] = {"": "", "s": ""}
#: Map contexts to RegistryCache
self._cache = RegistryCache()
@@ -326,7 +318,7 @@ class PlainRegistry(metaclass=RegistryMeta):
self._register_adder(DimensionDefinition, self._add_dimension)
self._register_adder(DerivedDimensionDefinition, self._add_derived_dimension)
- def __deepcopy__(self, memo) -> "PlainRegistry":
+ def __deepcopy__(self, memo) -> PlainRegistry:
new = object.__new__(type(self))
new.__dict__ = copy.deepcopy(self.__dict__, memo)
new._init_dynamic_classes()
@@ -351,7 +343,7 @@ class PlainRegistry(metaclass=RegistryMeta):
except UndefinedUnitError:
return False
- def __dir__(self) -> List[str]:
+ def __dir__(self) -> list[str]:
#: Calling dir(registry) gives all units, methods, and attributes.
#: Also used for autocompletion in IPython.
return list(self._units.keys()) + list(object.__dir__(self))
@@ -365,7 +357,7 @@ class PlainRegistry(metaclass=RegistryMeta):
"""
return iter(sorted(self._units.keys()))
- def set_fmt_locale(self, loc: Optional[str]) -> None:
+ def set_fmt_locale(self, loc: str | None) -> None:
"""Change the locale used by default by `format_babel`.
Parameters
@@ -397,7 +389,7 @@ class PlainRegistry(metaclass=RegistryMeta):
self.Measurement.default_format = value
@property
- def cache_folder(self) -> Optional[pathlib.Path]:
+ def cache_folder(self) -> pathlib.Path | None:
if self._diskcache:
return self._diskcache.cache_folder
return None
@@ -472,7 +464,7 @@ class PlainRegistry(metaclass=RegistryMeta):
if self._on_redefinition == "raise":
raise RedefinitionError(key, type(value))
elif self._on_redefinition == "warn":
- logger.warning("Redefining '%s' (%s)" % (key, type(value)))
+ logger.warning("Redefining '{}' ({})".format(key, type(value)))
target_dict[key] = value
if casei_target_dict is not None:
@@ -581,9 +573,7 @@ class PlainRegistry(metaclass=RegistryMeta):
logger.warning(f"Could not resolve {unit_name}: {exc!r}")
return self._cache
- def get_name(
- self, name_or_alias: str, case_sensitive: Optional[bool] = None
- ) -> str:
+ def get_name(self, name_or_alias: str, case_sensitive: bool | None = None) -> str:
"""Return the canonical name of a unit."""
if name_or_alias == "dimensionless":
@@ -621,9 +611,7 @@ class PlainRegistry(metaclass=RegistryMeta):
return unit_name
- def get_symbol(
- self, name_or_alias: str, case_sensitive: Optional[bool] = None
- ) -> str:
+ def get_symbol(self, name_or_alias: str, case_sensitive: bool | None = None) -> str:
"""Return the preferred alias for a unit."""
candidates = self.parse_unit_name(name_or_alias, case_sensitive)
if not candidates:
@@ -632,8 +620,8 @@ class PlainRegistry(metaclass=RegistryMeta):
prefix, unit_name, _ = candidates[0]
else:
logger.warning(
- "Parsing {0} yield multiple results. "
- "Options are: {1!r}".format(name_or_alias, candidates)
+ "Parsing {} yield multiple results. "
+ "Options are: {!r}".format(name_or_alias, candidates)
)
prefix, unit_name, _ = candidates[0]
@@ -654,7 +642,7 @@ class PlainRegistry(metaclass=RegistryMeta):
return self._get_dimensionality(input_units)
def _get_dimensionality(
- self, input_units: Optional[UnitsContainerT]
+ self, input_units: UnitsContainerT | None
) -> UnitsContainerT:
"""Convert a UnitsContainer to plain dimensions."""
if not input_units:
@@ -727,7 +715,7 @@ class PlainRegistry(metaclass=RegistryMeta):
def get_root_units(
self, input_units: UnitLike, check_nonmult: bool = True
- ) -> Tuple[Number, PlainUnit]:
+ ) -> tuple[Number, PlainUnit]:
"""Convert unit or dict of units to the root units.
If any unit is non multiplicative and check_converter is True,
@@ -840,7 +828,7 @@ class PlainRegistry(metaclass=RegistryMeta):
def get_compatible_units(
self, input_units, group_or_system=None
- ) -> FrozenSet[Unit]:
+ ) -> frozenset[Unit]:
""" """
input_units = to_units_container(input_units)
@@ -858,7 +846,7 @@ class PlainRegistry(metaclass=RegistryMeta):
# TODO: remove context from here
def is_compatible_with(
- self, obj1: Any, obj2: Any, *contexts: Union[str, Context], **ctx_kwargs
+ self, obj1: Any, obj2: Any, *contexts: str | Context, **ctx_kwargs
) -> bool:
"""check if the other object is compatible
@@ -972,8 +960,8 @@ class PlainRegistry(metaclass=RegistryMeta):
return value
def parse_unit_name(
- self, unit_name: str, case_sensitive: Optional[bool] = None
- ) -> Tuple[Tuple[str, str, str], ...]:
+ self, unit_name: str, case_sensitive: bool | None = None
+ ) -> tuple[tuple[str, str, str], ...]:
"""Parse a unit to identify prefix, unit name and suffix
by walking the list of prefix and suffix.
In case of equivalent combinations (e.g. ('kilo', 'gram', '') and
@@ -997,8 +985,8 @@ class PlainRegistry(metaclass=RegistryMeta):
)
def _parse_unit_name(
- self, unit_name: str, case_sensitive: Optional[bool] = None
- ) -> Iterator[Tuple[str, str, str]]:
+ self, unit_name: str, case_sensitive: bool | None = None
+ ) -> Iterator[tuple[str, str, str]]:
"""Helper of parse_unit_name."""
case_sensitive = (
self.case_sensitive if case_sensitive is None else case_sensitive
@@ -1029,8 +1017,8 @@ class PlainRegistry(metaclass=RegistryMeta):
@staticmethod
def _dedup_candidates(
- candidates: Iterable[Tuple[str, str, str]]
- ) -> Tuple[Tuple[str, str, str], ...]:
+ candidates: Iterable[tuple[str, str, str]]
+ ) -> tuple[tuple[str, str, str], ...]:
"""Helper of parse_unit_name.
Given an iterable of unit triplets (prefix, name, suffix), remove those with
@@ -1051,8 +1039,8 @@ class PlainRegistry(metaclass=RegistryMeta):
def parse_units(
self,
input_string: str,
- as_delta: Optional[bool] = None,
- case_sensitive: Optional[bool] = None,
+ as_delta: bool | None = None,
+ case_sensitive: bool | None = None,
) -> Unit:
"""Parse a units expression and returns a UnitContainer with
the canonical names.
@@ -1083,7 +1071,7 @@ class PlainRegistry(metaclass=RegistryMeta):
self,
input_string: str,
as_delta: bool = True,
- case_sensitive: Optional[bool] = None,
+ case_sensitive: bool | None = None,
) -> UnitsContainerT:
"""Parse a units expression and returns a UnitContainer with
the canonical names.
@@ -1152,9 +1140,9 @@ class PlainRegistry(metaclass=RegistryMeta):
self,
input_string: str,
pattern: str,
- case_sensitive: Optional[bool] = None,
+ case_sensitive: bool | None = None,
many: bool = False,
- ) -> Union[List[str], str, None]:
+ ) -> list[str] | str | None:
"""Parse a string with a given regex pattern and returns result.
Parameters
@@ -1206,7 +1194,7 @@ class PlainRegistry(metaclass=RegistryMeta):
def parse_expression(
self,
input_string: str,
- case_sensitive: Optional[bool] = None,
+ case_sensitive: bool | None = None,
**values,
) -> Quantity:
"""Parse a mathematical expression including units and return a quantity object.
diff --git a/pint/facets/plain/unit.py b/pint/facets/plain/unit.py
index b608c05..c8726ec 100644
--- a/pint/facets/plain/unit.py
+++ b/pint/facets/plain/unit.py
@@ -12,7 +12,7 @@ import copy
import locale
import operator
from numbers import Number
-from typing import TYPE_CHECKING, Any, Union
+from typing import TYPE_CHECKING, Any
from ..._typing import UnitLike
from ...compat import NUMERIC_TYPES
@@ -65,7 +65,7 @@ class PlainUnit(PrettyIPython, SharedRegistryObject):
return str(self).encode(locale.getpreferredencoding())
def __repr__(self) -> str:
- return "<Unit('{}')>".format(self._units)
+ return f"<Unit('{self._units}')>"
@property
def dimensionless(self) -> bool:
@@ -96,7 +96,7 @@ class PlainUnit(PrettyIPython, SharedRegistryObject):
return self._REGISTRY.get_compatible_units(self)
def is_compatible_with(
- self, other: Any, *contexts: Union[str, Context], **ctx_kwargs: Any
+ self, other: Any, *contexts: str | Context, **ctx_kwargs: Any
) -> bool:
"""check if the other object is compatible
@@ -171,12 +171,12 @@ class PlainUnit(PrettyIPython, SharedRegistryObject):
__div__ = __truediv__
__rdiv__ = __rtruediv__
- def __pow__(self, other) -> "PlainUnit":
+ def __pow__(self, other) -> PlainUnit:
if isinstance(other, NUMERIC_TYPES):
return self.__class__(self._units**other)
else:
- mess = "Cannot power PlainUnit by {}".format(type(other))
+ mess = f"Cannot power PlainUnit by {type(other)}"
raise TypeError(mess)
def __hash__(self) -> int:
diff --git a/pint/facets/system/registry.py b/pint/facets/system/registry.py
index 527440a..82edc03 100644
--- a/pint/facets/system/registry.py
+++ b/pint/facets/system/registry.py
@@ -9,7 +9,7 @@
from __future__ import annotations
from numbers import Number
-from typing import TYPE_CHECKING, Dict, FrozenSet, Tuple, Union
+from typing import TYPE_CHECKING
from ... import errors
@@ -53,7 +53,7 @@ class SystemRegistry(GroupRegistry):
#: Map system name to system.
#: :type: dict[ str | System]
- self._systems: Dict[str, System] = {}
+ self._systems: dict[str, System] = {}
#: Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer)
self._base_units_cache = dict()
@@ -143,10 +143,10 @@ class SystemRegistry(GroupRegistry):
def get_base_units(
self,
- input_units: Union[UnitLike, Quantity],
+ input_units: UnitLike | Quantity,
check_nonmult: bool = True,
- system: Union[str, System, None] = None,
- ) -> Tuple[Number, Unit]:
+ system: str | System | None = None,
+ ) -> tuple[Number, Unit]:
"""Convert unit or dict of units to the plain units.
If any unit is non multiplicative and check_converter is True,
@@ -183,7 +183,7 @@ class SystemRegistry(GroupRegistry):
self,
input_units: UnitsContainerT,
check_nonmult: bool = True,
- system: Union[str, System, None] = None,
+ system: str | System | None = None,
):
if system is None:
system = self._default_system
@@ -224,7 +224,7 @@ class SystemRegistry(GroupRegistry):
return base_factor, destination_units
- def _get_compatible_units(self, input_units, group_or_system) -> FrozenSet[Unit]:
+ def _get_compatible_units(self, input_units, group_or_system) -> frozenset[Unit]:
if group_or_system is None:
group_or_system = self._default_system