Skip to content

Commit

Permalink
refactor: run 'pyupgrade --py310-plus **/*.py'
Browse files Browse the repository at this point in the history
  • Loading branch information
hgrecco committed Mar 9, 2024
1 parent 1a87ce4 commit bdf7d7b
Show file tree
Hide file tree
Showing 34 changed files with 166 additions and 175 deletions.
3 changes: 2 additions & 1 deletion pint/_typing.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, Protocol
from typing import TYPE_CHECKING, Any, TypeVar, Union, Protocol
from collections.abc import Callable
from decimal import Decimal
from fractions import Fraction

Expand Down
18 changes: 8 additions & 10 deletions pint/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from importlib import import_module
from numbers import Number
from collections.abc import Mapping
from typing import Any, NoReturn, Callable, Optional, Union
from typing import Any, NoReturn
from collections.abc import Callable
from collections.abc import Iterable

try:
Expand All @@ -29,10 +30,7 @@
HAS_UNCERTAINTIES = False


if sys.version_info >= (3, 10):
from typing import TypeAlias # noqa
else:
from typing_extensions import TypeAlias # noqa
from typing import TypeAlias # noqa


if sys.version_info >= (3, 11):
Expand Down Expand Up @@ -60,7 +58,7 @@


def missing_dependency(
package: str, display_name: Optional[str] = None
package: str, display_name: str | None = None
) -> Callable[..., NoReturn]:
"""Return a helper function that raises an exception when used.
Expand Down Expand Up @@ -236,7 +234,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, 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:
Expand Down Expand Up @@ -297,7 +295,7 @@ def is_duck_array(obj: type) -> bool:
return is_duck_array_type(type(obj))


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


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


def zero_or_nan(obj: Any, check_all: bool) -> Union[bool, Iterable[bool]]:
def zero_or_nan(obj: Any, check_all: bool) -> 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, Optional, ClassVar
from typing import Any, ClassVar

from ._typing import Magnitude

Expand Down Expand Up @@ -51,7 +51,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) -> Optional[dict[str, Any]]:
def preprocess_kwargs(cls, **kwargs: Any) -> dict[str, Any] | None:
return None

@classmethod
Expand Down
4 changes: 1 addition & 3 deletions pint/delegates/formatter/_format_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@
from functools import partial
from typing import (
Any,
Generator,
Iterable,
TypeVar,
Callable,
TYPE_CHECKING,
Literal,
TypedDict,
)
from collections.abc import Generator, Iterable, Callable

from locale import getlocale, setlocale, LC_NUMERIC
from contextlib import contextmanager
Expand Down
3 changes: 2 additions & 1 deletion pint/delegates/formatter/_spec_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

from __future__ import annotations

from typing import Iterable, Callable, Any
from typing import Any
from collections.abc import Iterable, Callable
import warnings
from ...compat import Number
import re
Expand Down
3 changes: 2 additions & 1 deletion pint/delegates/formatter/_to_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Callable
from typing import TYPE_CHECKING
from collections.abc import Callable
from ...compat import ndarray, np, Unpack
from ._spec_helpers import split_format, join_mu, REGISTERED_FORMATTERS

Expand Down
17 changes: 9 additions & 8 deletions pint/delegates/formatter/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Callable, Iterable, Literal, Optional, Any
from typing import TYPE_CHECKING, Literal, Any
from collections.abc import Callable, Iterable
import locale
from ...compat import babel_parse, Number, Unpack
from ...util import iterable
Expand Down Expand Up @@ -54,17 +55,17 @@ class FullFormatter:
"[time]",
"[temperature]",
)
default_sort_func: Optional[
default_sort_func: None | (
Callable[
[Iterable[tuple[str, Number]], GenericPlainRegistry],
Iterable[tuple[str, Number]],
]
] = lambda self, x, registry: sorted(x)
) = lambda self, x, registry: sorted(x)

locale: Optional[Locale] = None
locale: Locale | None = None
babel_length: Literal["short", "long", "narrow"] = "long"

def set_locale(self, loc: Optional[str]) -> None:
def set_locale(self, loc: str | None) -> None:
"""Change the locale used by default by `format_babel`.
Parameters
Expand Down Expand Up @@ -183,8 +184,8 @@ def format_unit_babel(
self,
unit: PlainUnit,
spec: str = "",
length: Optional[Literal["short", "long", "narrow"]] = "long",
locale: Optional[Locale] = None,
length: Literal["short", "long", "narrow"] | None = "long",
locale: Locale | None = None,
) -> str:
if self.locale is None and locale is None:
raise ValueError(
Expand All @@ -204,7 +205,7 @@ def format_quantity_babel(
quantity: PlainQuantity[MagnitudeT],
spec: str = "",
length: Literal["short", "long", "narrow"] = "long",
locale: Optional[Locale] = None,
locale: Locale | None = None,
) -> str:
if self.locale is None and locale is None:
raise ValueError(
Expand Down
7 changes: 4 additions & 3 deletions pint/delegates/formatter/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
from __future__ import annotations
import functools

from typing import TYPE_CHECKING, Any, Iterable, Union
from typing import TYPE_CHECKING, Any
from collections.abc import Iterable

import re
from ._spec_helpers import split_format, FORMATTER
Expand Down Expand Up @@ -110,7 +111,7 @@ def siunitx_format_unit(
) -> str:
"""Returns LaTeX code for the unit that can be put into an siunitx command."""

def _tothe(power: Union[int, float]) -> str:
def _tothe(power: int | float) -> str:
if isinstance(power, int) or (isinstance(power, float) and power.is_integer()):
if power == 1:
return ""
Expand Down Expand Up @@ -241,7 +242,7 @@ def format_measurement(
if "L" not in unc_spec:
unc_spec += "L"

joint_fstring = "{}\ {}"
joint_fstring = r"{}\ {}"

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

import flexparser as fp
Expand All @@ -35,7 +35,7 @@

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

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

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

import flexcache as fc
import flexparser as fp
Expand Down Expand Up @@ -119,7 +118,7 @@ def iter_parsed_project(
yield stmt

def parse_file(
self, filename: Union[pathlib.Path, str], cfg: Optional[ParserConfig] = None
self, filename: pathlib.Path | str, cfg: ParserConfig | None = None
) -> fp.ParsedProject[PintRootBlock, ParserConfig]:
return fp.parse(
filename,
Expand All @@ -131,7 +130,7 @@ def parse_file(
)

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

from __future__ import annotations

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

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

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

def __str__(self):
if isinstance(self.unit_names, str):
Expand Down
3 changes: 2 additions & 1 deletion pint/facets/context/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
import numbers
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
from typing import TYPE_CHECKING
from collections.abc import Callable
from collections.abc import Iterable

from ... import errors
Expand Down
19 changes: 10 additions & 9 deletions pint/facets/context/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

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

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

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

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

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

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

def insert_contexts(self, *contexts: Context):
"""Insert one or more contexts in reversed order the chained map.
Expand All @@ -292,7 +293,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: Optional[int] = None):
def remove_contexts(self, n: int | None = None):
"""Remove the last n inserted contexts from the chain.
Parameters
Expand Down
Loading

0 comments on commit bdf7d7b

Please sign in to comment.