diff options
author | Hernan Grecco <hgrecco@gmail.com> | 2023-04-29 19:44:20 -0300 |
---|---|---|
committer | Hernan Grecco <hgrecco@gmail.com> | 2023-04-29 19:44:20 -0300 |
commit | b63697287ba1e5de7300890ea4c03b8781b04863 (patch) | |
tree | 0eb5db03beef71ddfb5a094521034b9f0b212b5b | |
parent | 10f69c4870ef9acda1b5dd21f2bf87f15855d3ea (diff) | |
download | pint-b63697287ba1e5de7300890ea4c03b8781b04863.tar.gz |
Run pyupgrade --py39-plus in all files except _vendor
40 files changed, 208 insertions, 238 deletions
diff --git a/benchmarks/benchmarks/20_quantity.py b/benchmarks/benchmarks/20_quantity.py index c0174ef..3283ede 100644 --- a/benchmarks/benchmarks/20_quantity.py +++ b/benchmarks/benchmarks/20_quantity.py @@ -8,7 +8,7 @@ from . import util units = ("meter", "kilometer", "second", "minute", "angstrom") all_values = ("int", "float", "complex") all_values_q = tuple( - "%s_%s" % (a, b) for a, b in it.product(all_values, ("meter", "kilometer")) + "{}_{}".format(a, b) for a, b in it.product(all_values, ("meter", "kilometer")) ) op1 = (operator.neg, operator.truth) diff --git a/benchmarks/benchmarks/30_numpy.py b/benchmarks/benchmarks/30_numpy.py index 15ae66c..e2b0f5f 100644 --- a/benchmarks/benchmarks/30_numpy.py +++ b/benchmarks/benchmarks/30_numpy.py @@ -9,11 +9,11 @@ from . import util lengths = ("short", "mid") all_values = tuple( - "%s_%s" % (a, b) for a, b in it.product(lengths, ("list", "tuple", "array")) + "{}_{}".format(a, b) for a, b in it.product(lengths, ("list", "tuple", "array")) ) all_arrays = ("short_array", "mid_array") units = ("meter", "kilometer") -all_arrays_q = tuple("%s_%s" % (a, b) for a, b in it.product(all_arrays, units)) +all_arrays_q = tuple("{}_{}".format(a, b) for a, b in it.product(all_arrays, units)) ureg = None data = {} diff --git a/pint/_typing.py b/pint/_typing.py index 64c3a2b..1dc3ea6 100644 --- a/pint/_typing.py +++ b/pint/_typing.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Callable, Tuple, TypeVar, Union +from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union if TYPE_CHECKING: from .facets.plain import PlainQuantity as Quantity @@ -11,7 +11,7 @@ UnitLike = Union[str, "UnitsContainer", "Unit"] QuantityOrUnitLike = Union["Quantity", UnitLike] -Shape = Tuple[int, ...] +Shape = tuple[int, ...] _MagnitudeType = TypeVar("_MagnitudeType") S = TypeVar("S") diff --git a/pint/compat.py b/pint/compat.py index c585455..ee8d443 100644 --- a/pint/compat.py +++ b/pint/compat.py @@ -16,7 +16,7 @@ from decimal import Decimal from importlib import import_module from io import BytesIO from numbers import Number -from typing import Mapping, Optional +from collections.abc import Mapping def missing_dependency(package, display_name=None): @@ -53,7 +53,7 @@ try: def _to_magnitude(value, force_ndarray=False, force_ndarray_like=False): if isinstance(value, (dict, bool)) or value is None: - raise TypeError("Invalid magnitude for Quantity: {0!r}".format(value)) + raise TypeError(f"Invalid magnitude for Quantity: {value!r}") elif isinstance(value, str) and value == "": raise ValueError("Quantity magnitude cannot be an empty string.") elif isinstance(value, (list, tuple)): @@ -102,7 +102,7 @@ except ImportError: "Cannot force to ndarray or ndarray-like when NumPy is not present." ) elif isinstance(value, (dict, bool)) or value is None: - raise TypeError("Invalid magnitude for Quantity: {0!r}".format(value)) + raise TypeError(f"Invalid magnitude for Quantity: {value!r}") elif isinstance(value, str) and value == "": raise ValueError("Quantity magnitude cannot be an empty string.") elif isinstance(value, (list, tuple)): @@ -186,7 +186,7 @@ upcast_type_names = ( "xarray.core.dataarray.DataArray", ) -upcast_type_map: Mapping[str : Optional[type]] = {k: None for k in upcast_type_names} +upcast_type_map: Mapping[str : type | None] = {k: None for k in upcast_type_names} def fully_qualified_name(t: type) -> str: diff --git a/pint/converters.py b/pint/converters.py index 12248a8..9b8513f 100644 --- a/pint/converters.py +++ b/pint/converters.py @@ -44,7 +44,7 @@ class Converter: @classmethod def get_field_names(cls, new_cls): - return frozenset((p.name for p in dc_fields(new_cls))) + return frozenset(p.name for p in dc_fields(new_cls)) @classmethod def preprocess_kwargs(cls, **kwargs): @@ -57,7 +57,7 @@ class Converter: new_cls = cls._param_names_to_subclass[kwk] except KeyError: for new_cls in cls._subclasses: - p_names = frozenset((p.name for p in dc_fields(new_cls))) + p_names = frozenset(p.name for p in dc_fields(new_cls)) if p_names == kwk: cls._param_names_to_subclass[kwk] = new_cls break diff --git a/pint/delegates/base_defparser.py b/pint/delegates/base_defparser.py index d35f3e3..774f404 100644 --- a/pint/delegates/base_defparser.py +++ b/pint/delegates/base_defparser.py @@ -67,7 +67,7 @@ class ParserConfig: return val.scale -@functools.lru_cache() +@functools.lru_cache def build_disk_cache_class(non_int_type: type): """Build disk cache class, taking into account the non_int_type.""" diff --git a/pint/delegates/txt_defparser/context.py b/pint/delegates/txt_defparser/context.py index 5c54b4c..b7e5a67 100644 --- a/pint/delegates/txt_defparser/context.py +++ b/pint/delegates/txt_defparser/context.py @@ -20,7 +20,6 @@ import numbers import re import typing as ty from dataclasses import dataclass -from typing import Dict, Tuple from ..._vendor import flexparser as fp from ...facets.context import definitions @@ -92,8 +91,8 @@ class BeginContext(fp.ParsedStatement): ) name: str - aliases: Tuple[str, ...] - defaults: Dict[str, numbers.Number] + aliases: tuple[str, ...] + defaults: dict[str, numbers.Number] @classmethod def from_string_and_config( diff --git a/pint/delegates/txt_defparser/plain.py b/pint/delegates/txt_defparser/plain.py index 428df10..749e7fd 100644 --- a/pint/delegates/txt_defparser/plain.py +++ b/pint/delegates/txt_defparser/plain.py @@ -159,10 +159,10 @@ class UnitDefinition(fp.ParsedStatement, definitions.UnitDefinition): [converter, modifiers] = value.split(";", 1) try: - modifiers = dict( - (key.strip(), config.to_number(value)) + modifiers = { + key.strip(): config.to_number(value) for key, value in (part.split(":") for part in modifiers.split(";")) - ) + } except definitions.NotNumeric as ex: return common.DefinitionSyntaxError( f"Unit definition ('{name}') must contain only numbers in modifier, not {ex.value}" 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 diff --git a/pint/formatting.py b/pint/formatting.py index f450d5f..c12000f 100644 --- a/pint/formatting.py +++ b/pint/formatting.py @@ -13,7 +13,7 @@ from __future__ import annotations import functools import re import warnings -from typing import Callable, Dict +from typing import Callable from .babel_names import _babel_lengths, _babel_units from .compat import babel_parse @@ -76,7 +76,7 @@ def _pretty_fmt_exponent(num): #: _FORMATS maps format specifications to the corresponding argument set to #: formatter(). -_FORMATS: Dict[str, dict] = { +_FORMATS: dict[str, dict] = { "P": { # Pretty format. "as_ratio": True, "single_denominator": False, @@ -122,7 +122,7 @@ _FORMATS: Dict[str, dict] = { } #: _FORMATTERS maps format names to callables doing the formatting -_FORMATTERS: Dict[str, Callable] = {} +_FORMATTERS: dict[str, Callable] = {} def register_unit_format(name): @@ -197,9 +197,7 @@ def latex_escape(string): @register_unit_format("L") def format_latex(unit, registry, **options): - preprocessed = { - r"\mathrm{{{}}}".format(latex_escape(u)): p for u, p in unit.items() - } + preprocessed = {rf"\mathrm{{{latex_escape(u)}}}": p for u, p in unit.items()} formatted = formatter( preprocessed.items(), as_ratio=True, @@ -442,10 +440,10 @@ def siunitx_format_unit(units, registry): elif power == 3: return r"\cubed" else: - return r"\tothe{{{:d}}}".format(int(power)) + return rf"\tothe{{{int(power):d}}}" else: # limit float powers to 3 decimal places - return r"\tothe{{{:.3f}}}".format(power).rstrip("0") + return rf"\tothe{{{power:.3f}}}".rstrip("0") lpos = [] lneg = [] @@ -466,9 +464,9 @@ def siunitx_format_unit(units, registry): if power < 0: lpick.append(r"\per") if prefix is not None: - lpick.append(r"\{}".format(prefix)) - lpick.append(r"\{}".format(unit)) - lpick.append(r"{}".format(_tothe(abs(power)))) + lpick.append(rf"\{prefix}") + lpick.append(rf"\{unit}") + lpick.append(rf"{_tothe(abs(power))}") return "".join(lpos) + "".join(lneg) diff --git a/pint/pint_convert.py b/pint/pint_convert.py index d8d60e8..86d8a7a 100755 --- a/pint/pint_convert.py +++ b/pint/pint_convert.py @@ -160,7 +160,7 @@ if args.unc: def convert(u_from, u_to=None, unc=None, factor=None): q = ureg.Quantity(u_from) - fmt = ".{}g".format(args.prec) + fmt = f".{args.prec}g" if unc: q = q.plus_minus(unc) if u_to: @@ -172,7 +172,7 @@ def convert(u_from, u_to=None, unc=None, factor=None): nq *= ureg.Quantity(factor).to_base_units() prec_unc = use_unc(nq.magnitude, fmt, args.prec_unc) if prec_unc > 0: - fmt = ".{}uS".format(prec_unc) + fmt = f".{prec_unc}uS" else: try: nq = nq.magnitude.n * nq.units diff --git a/pint/pint_eval.py b/pint/pint_eval.py index 2054260..4b5b84c 100644 --- a/pint/pint_eval.py +++ b/pint/pint_eval.py @@ -124,7 +124,7 @@ class EvalTreeNode: return define_op(self.left) -from typing import Iterable +from collections.abc import Iterable def build_eval_tree( diff --git a/pint/registry_helpers.py b/pint/registry_helpers.py index 07b00ff..1f28036 100644 --- a/pint/registry_helpers.py +++ b/pint/registry_helpers.py @@ -13,7 +13,8 @@ from __future__ import annotations import functools from inspect import signature from itertools import zip_longest -from typing import TYPE_CHECKING, Callable, Iterable, TypeVar, Union +from typing import TYPE_CHECKING, Callable, TypeVar +from collections.abc import Iterable from ._typing import F from .errors import DimensionalityError @@ -184,9 +185,9 @@ def _apply_defaults(func, args, kwargs): def wraps( - ureg: "UnitRegistry", - ret: Union[str, "Unit", Iterable[Union[str, "Unit", None]], None], - args: Union[str, "Unit", Iterable[Union[str, "Unit", None]], None], + ureg: UnitRegistry, + ret: str | Unit | Iterable[str | Unit | None] | None, + args: str | Unit | Iterable[str | Unit | None] | None, strict: bool = True, ) -> Callable[[Callable[..., T]], Callable[..., Quantity[T]]]: """Wraps a function to become pint-aware. @@ -300,7 +301,7 @@ def wraps( def check( - ureg: "UnitRegistry", *args: Union[str, UnitsContainer, "Unit", None] + ureg: UnitRegistry, *args: str | UnitsContainer | Unit | None ) -> Callable[[F], F]: """Decorator to for quantity type checking for function inputs. diff --git a/pint/testing.py b/pint/testing.py index 1c458f5..2f201f0 100644 --- a/pint/testing.py +++ b/pint/testing.py @@ -36,10 +36,10 @@ def _get_comparable_magnitudes(first, second, msg): def assert_equal(first, second, msg=None): if msg is None: - msg = "Comparing %r and %r. " % (first, second) + msg = "Comparing {!r} and {!r}. ".format(first, second) m1, m2 = _get_comparable_magnitudes(first, second, msg) - msg += " (Converted to %r and %r): Magnitudes are not equal" % (m1, m2) + msg += " (Converted to {!r} and {!r}): Magnitudes are not equal".format(m1, m2) if isinstance(m1, ndarray) or isinstance(m2, ndarray): np.testing.assert_array_equal(m1, m2, err_msg=msg) @@ -60,15 +60,15 @@ def assert_equal(first, second, msg=None): def assert_allclose(first, second, rtol=1e-07, atol=0, msg=None): if msg is None: try: - msg = "Comparing %r and %r. " % (first, second) + msg = "Comparing {!r} and {!r}. ".format(first, second) except TypeError: try: - msg = "Comparing %s and %s. " % (first, second) + msg = "Comparing {} and {}. ".format(first, second) except Exception: msg = "Comparing" m1, m2 = _get_comparable_magnitudes(first, second, msg) - msg += " (Converted to %r and %r)" % (m1, m2) + msg += " (Converted to {!r} and {!r})".format(m1, m2) if isinstance(m1, ndarray) or isinstance(m2, ndarray): np.testing.assert_allclose(m1, m2, rtol=rtol, atol=atol, err_msg=msg) diff --git a/pint/testsuite/test_babel.py b/pint/testsuite/test_babel.py index 5c32879..7842d54 100644 --- a/pint/testsuite/test_babel.py +++ b/pint/testsuite/test_babel.py @@ -84,16 +84,16 @@ def test_str(func_registry): s = "24.0 meter" assert str(d) == s assert "%s" % d == s - assert "{}".format(d) == s + assert f"{d}" == s ureg.set_fmt_locale("fr_FR") s = "24.0 mètres" assert str(d) == s assert "%s" % d == s - assert "{}".format(d) == s + assert f"{d}" == s ureg.set_fmt_locale(None) s = "24.0 meter" assert str(d) == s assert "%s" % d == s - assert "{}".format(d) == s + assert f"{d}" == s diff --git a/pint/testsuite/test_compat_upcast.py b/pint/testsuite/test_compat_upcast.py index ad267c1..56996b9 100644 --- a/pint/testsuite/test_compat_upcast.py +++ b/pint/testsuite/test_compat_upcast.py @@ -126,9 +126,7 @@ def test_array_function_deferral(da, module_registry): upper = 3 * module_registry.m args = (da, lower, upper) assert ( - lower.__array_function__( - np.clip, tuple(set(type(arg) for arg in args)), args, {} - ) + lower.__array_function__(np.clip, tuple({type(arg) for arg in args}), args, {}) is NotImplemented ) diff --git a/pint/testsuite/test_contexts.py b/pint/testsuite/test_contexts.py index c7551e4..ea6525d 100644 --- a/pint/testsuite/test_contexts.py +++ b/pint/testsuite/test_contexts.py @@ -683,7 +683,7 @@ class TestDefinedContexts: ) p = find_shortest_path(ureg._active_ctx.graph, da, db) assert p - msg = "{} <-> {}".format(a, b) + msg = f"{a} <-> {b}" # assertAlmostEqualRelError converts second to first helpers.assert_quantity_almost_equal(b, a, rtol=0.01, msg=msg) @@ -705,7 +705,7 @@ class TestDefinedContexts: da, db = Context.__keytransform__(a.dimensionality, b.dimensionality) p = find_shortest_path(ureg._active_ctx.graph, da, db) assert p - msg = "{} <-> {}".format(a, b) + msg = f"{a} <-> {b}" helpers.assert_quantity_almost_equal(b, a, rtol=0.01, msg=msg) # Check RKM <-> cN/tex conversion diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index 8517bd9..9540814 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -445,10 +445,10 @@ class TestIssues(QuantityTestCase): def test_issue354_356_370(self, module_registry): assert ( - "{:~}".format(1 * module_registry.second / module_registry.millisecond) + f"{1 * module_registry.second / module_registry.millisecond:~}" == "1.0 s / ms" ) - assert "{:~}".format(1 * module_registry.count) == "1 count" + assert f"{1 * module_registry.count:~}" == "1 count" assert "{:~}".format(1 * module_registry("MiB")) == "1 MiB" def test_issue468(self, module_registry): diff --git a/pint/testsuite/test_measurement.py b/pint/testsuite/test_measurement.py index b78ca0e..9de2762 100644 --- a/pint/testsuite/test_measurement.py +++ b/pint/testsuite/test_measurement.py @@ -178,7 +178,7 @@ class TestMeasurement(QuantityTestCase): ): with subtests.test(spec): self.ureg.default_format = spec - assert "{}".format(m) == result + assert f"{m}" == result def test_raise_build(self): v, u = self.Q_(1.0, "s"), self.Q_(0.1, "s") diff --git a/pint/testsuite/test_non_int.py b/pint/testsuite/test_non_int.py index 66637e1..d0b27ae 100644 --- a/pint/testsuite/test_non_int.py +++ b/pint/testsuite/test_non_int.py @@ -740,10 +740,10 @@ class _TestQuantityBasicMath(NonIntTypeTestCase): zy = self.Q_(fun(y.magnitude), "meter") rx = fun(x) ry = fun(y) - assert rx == zx, "while testing {0}".format(fun) - assert ry == zy, "while testing {0}".format(fun) - assert rx is not zx, "while testing {0}".format(fun) - assert ry is not zy, "while testing {0}".format(fun) + assert rx == zx, f"while testing {fun}" + assert ry == zy, f"while testing {fun}" + assert rx is not zx, f"while testing {fun}" + assert ry is not zy, f"while testing {fun}" def test_quantity_float_complex(self): x = self.QP_("-4.2", None) diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py index 8fb712a..18a56ab 100644 --- a/pint/testsuite/test_quantity.py +++ b/pint/testsuite/test_quantity.py @@ -1050,10 +1050,10 @@ class TestQuantityBasicMath(QuantityTestCase): zy = self.Q_(fun(y.magnitude), "meter") rx = fun(x) ry = fun(y) - assert rx == zx, "while testing {0}".format(fun) - assert ry == zy, "while testing {0}".format(fun) - assert rx is not zx, "while testing {0}".format(fun) - assert ry is not zy, "while testing {0}".format(fun) + assert rx == zx, f"while testing {fun}" + assert ry == zy, f"while testing {fun}" + assert rx is not zx, f"while testing {fun}" + assert ry is not zy, f"while testing {fun}" def test_quantity_float_complex(self): x = self.Q_(-4.2, None) diff --git a/pint/testsuite/test_umath.py b/pint/testsuite/test_umath.py index 6f32ab5..73d0ae7 100644 --- a/pint/testsuite/test_umath.py +++ b/pint/testsuite/test_umath.py @@ -79,7 +79,7 @@ class TestUFuncs: if results is None: results = [None] * len(ok_with) for x1, res in zip(ok_with, results): - err_msg = "At {} with {}".format(func.__name__, x1) + err_msg = f"At {func.__name__} with {x1}" if output_units == "same": ou = x1.units elif isinstance(output_units, (int, float)): @@ -163,7 +163,7 @@ class TestUFuncs: if results is None: results = [None] * len(ok_with) for x1, res in zip(ok_with, results): - err_msg = "At {} with {}".format(func.__name__, x1) + err_msg = f"At {func.__name__} with {x1}" qms = func(x1) if res is None: res = func(x1.magnitude) @@ -223,7 +223,7 @@ class TestUFuncs: """ for x2 in ok_with: - err_msg = "At {} with {} and {}".format(func.__name__, x1, x2) + err_msg = f"At {func.__name__} with {x1} and {x2}" if output_units == "same": ou = x1.units elif output_units == "prod": diff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py index 98a4fcc..fcfb2ed 100644 --- a/pint/testsuite/test_unit.py +++ b/pint/testsuite/test_unit.py @@ -144,7 +144,7 @@ class TestUnit(QuantityTestCase): ureg = UnitRegistry() - assert "{:new}".format(ureg.m) == "new format" + assert f"{ureg.m:new}" == "new format" def test_ipython(self): alltext = [] diff --git a/pint/testsuite/test_util.py b/pint/testsuite/test_util.py index bfbc55d..82cda7a 100644 --- a/pint/testsuite/test_util.py +++ b/pint/testsuite/test_util.py @@ -353,12 +353,12 @@ class TestOtherUtils: # Test with list, string, generator, and scalar assert iterable([0, 1, 2, 3]) assert iterable("test") - assert iterable((i for i in range(5))) + assert iterable(i for i in range(5)) assert not iterable(0) def test_sized(self): # Test with list, string, generator, and scalar assert sized([0, 1, 2, 3]) assert sized("test") - assert not sized((i for i in range(5))) + assert not sized(i for i in range(5)) assert not sized(0) diff --git a/pint/util.py b/pint/util.py index eff3670..5814463 100644 --- a/pint/util.py +++ b/pint/util.py @@ -22,7 +22,7 @@ from functools import lru_cache, partial from logging import NullHandler from numbers import Number from token import NAME, NUMBER -from typing import TYPE_CHECKING, ClassVar, Optional, Type, Union +from typing import TYPE_CHECKING, ClassVar from .compat import NUMERIC_TYPES, tokenizer from .errors import DefinitionSyntaxError @@ -230,11 +230,11 @@ def pi_theorem(quantities, registry=None): max_den = max(f.denominator for f in rowi) neg = -1 if sum(f < 0 for f in rowi) > sum(f > 0 for f in rowi) else 1 results.append( - dict( - (q[0], neg * f.numerator * max_den / f.denominator) + { + q[0]: neg * f.numerator * max_den / f.denominator for q, f in zip(quant, rowi) if f.numerator != 0 - ) + } ) return results @@ -347,9 +347,9 @@ class UnitsContainer(Mapping): self._d = d for key, value in d.items(): if not isinstance(key, str): - raise TypeError("key must be a str, not {}".format(type(key))) + raise TypeError(f"key must be a str, not {type(key)}") if not isinstance(value, Number): - raise TypeError("value must be a number, not {}".format(type(value))) + raise TypeError(f"value must be a number, not {type(value)}") if not isinstance(value, int) and not isinstance(value, self._non_int_type): d[key] = self._non_int_type(value) self._hash = None @@ -455,9 +455,9 @@ class UnitsContainer(Mapping): def __repr__(self) -> str: tmp = "{%s}" % ", ".join( - ["'{}': {}".format(key, value) for key, value in sorted(self._d.items())] + [f"'{key}': {value}" for key, value in sorted(self._d.items())] ) - return "<UnitsContainer({})>".format(tmp) + return f"<UnitsContainer({tmp})>" def __format__(self, spec: str) -> str: return format_unit(self, spec) @@ -586,7 +586,7 @@ class ParserHelper(UnitsContainer): raise Exception("unknown token type") @classmethod - @lru_cache() + @lru_cache def from_string(cls, input_string, non_int_type=float): """Parse linear expression mathematical units and return a quantity object. @@ -682,15 +682,15 @@ class ParserHelper(UnitsContainer): def __str__(self): tmp = "{%s}" % ", ".join( - ["'{}': {}".format(key, value) for key, value in sorted(self._d.items())] + [f"'{key}': {value}" for key, value in sorted(self._d.items())] ) - return "{} {}".format(self.scale, tmp) + return f"{self.scale} {tmp}" def __repr__(self): tmp = "{%s}" % ", ".join( - ["'{}': {}".format(key, value) for key, value in sorted(self._d.items())] + [f"'{key}': {value}" for key, value in sorted(self._d.items())] ) - return "<ParserHelper({}, {})>".format(self.scale, tmp) + return f"<ParserHelper({self.scale}, {tmp})>" def __mul__(self, other): if isinstance(other, str): @@ -848,25 +848,25 @@ class PrettyIPython: def _repr_html_(self): if "~" in self.default_format: - return "{:~H}".format(self) + return f"{self:~H}" else: - return "{:H}".format(self) + return f"{self:H}" def _repr_latex_(self): if "~" in self.default_format: - return "${:~L}$".format(self) + return f"${self:~L}$" else: - return "${:L}$".format(self) + return f"${self:L}$" def _repr_pretty_(self, p, cycle): if "~" in self.default_format: - p.text("{:~P}".format(self)) + p.text(f"{self:~P}") else: - p.text("{:P}".format(self)) + p.text(f"{self:P}") def to_units_container( - unit_like: Union[UnitLike, Quantity], registry: Optional[UnitRegistry] = None + unit_like: UnitLike | Quantity, registry: UnitRegistry | None = None ) -> UnitsContainer: """Convert a unit compatible type to a UnitsContainer. @@ -899,7 +899,7 @@ def to_units_container( def infer_base_unit( - unit_like: Union[UnitLike, Quantity], registry: Optional[UnitRegistry] = None + unit_like: UnitLike | Quantity, registry: UnitRegistry | None = None ) -> UnitsContainer: """ Given a Quantity or UnitLike, give the UnitsContainer for it's plain units. @@ -968,7 +968,7 @@ def getattr_maybe_raise(self, item): or len(item.lstrip("_")) == 0 or (item.startswith("_") and not item.lstrip("_")[0].isdigit()) ): - raise AttributeError("%r object has no attribute %r" % (self, item)) + raise AttributeError("{!r} object has no attribute {!r}".format(self, item)) def iterable(y) -> bool: @@ -1017,7 +1017,7 @@ def _build_type(class_name: str, bases): return type(class_name, bases, dict()) -def build_dependent_class(registry_class, class_name: str, attribute_name: str) -> Type: +def build_dependent_class(registry_class, class_name: str, attribute_name: str) -> type: """Creates a class specifically for the given registry that subclass all the classes named by the registry bases in a specific attribute @@ -1038,7 +1038,7 @@ def build_dependent_class(registry_class, class_name: str, attribute_name: str) return _build_type(class_name, bases) -def create_class_with_registry(registry, base_class) -> Type: +def create_class_with_registry(registry, base_class) -> type: """Create new class inheriting from base_class and filling _REGISTRY class attribute with an actual instanced registry. """ |