Skip to content

Commit

Permalink
plainquantity
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewgsavage committed Jan 18, 2025
1 parent 8119033 commit 5aee334
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 35 deletions.
8 changes: 6 additions & 2 deletions pint/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ class BehaviorChangeWarning(UserWarning):
else:
NUMERIC_TYPES = (Number, Decimal, ndarray, np.number)

def _to_magnitude(value, force_ndarray: bool=False, force_ndarray_like: bool=False):
def _to_magnitude(
value, force_ndarray: bool = False, force_ndarray_like: bool = False
):
if isinstance(value, (dict, bool)) or value is None:
raise TypeError(f"Invalid magnitude for Quantity: {value!r}")
elif isinstance(value, str) and value == "":
Expand Down Expand Up @@ -149,7 +151,9 @@ class np_datetime64:
HAS_NUMPY_ARRAY_FUNCTION = False
NP_NO_VALUE = None

def _to_magnitude(value, force_ndarray: bool=False, force_ndarray_like: bool=False):
def _to_magnitude(
value, force_ndarray: bool = False, force_ndarray_like: bool = False
):
if force_ndarray or force_ndarray_like:
raise ValueError(
"Cannot force to ndarray or ndarray-like when NumPy is not present."
Expand Down
6 changes: 3 additions & 3 deletions pint/delegates/formatter/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def format_unit(
unit: PlainUnit | Iterable[tuple[str, Any]],
uspec: str = "",
sort_func: SortFunc | None = None,
**babel_kwds: Unpack[BabelKwds],
**babel_kwds: Unpack[BabelKwds] | Unpack[dict[str, None]],
) -> str:
uspec = uspec or self.default_format
sort_func = sort_func or self.default_sort_func
Expand All @@ -142,7 +142,7 @@ def format_quantity(
self,
quantity: PlainQuantity[MagnitudeT],
spec: str = "",
**babel_kwds: Unpack[BabelKwds],
**babel_kwds: Unpack[BabelKwds] | Unpack[dict[str, None]],
) -> str:
spec = spec or self.default_format
# If Compact is selected, do it at the beginning
Expand Down Expand Up @@ -179,7 +179,7 @@ def format_measurement(
self,
measurement: Measurement,
meas_spec: str = "",
**babel_kwds: Unpack[BabelKwds],
**babel_kwds: Unpack[BabelKwds] | Unpack[dict[str, None]],
) -> str:
meas_spec = meas_spec or self.default_format
# If Compact is selected, do it at the beginning
Expand Down
2 changes: 1 addition & 1 deletion pint/facets/measurement/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

class MeasurementQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]):
# Measurement support
def plus_minus(self, error, relative: bool=False):
def plus_minus(self, error, relative: bool = False):
if isinstance(error, self.__class__):
if relative:
raise ValueError(f"{error} is not a valid relative error.")
Expand Down
8 changes: 5 additions & 3 deletions pint/facets/numpy/numpy_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ def _unwrap(p, discont=None, axis=-1):


@implements("copyto", "function")
def _copyto(dst, src, casting="same_kind", where: bool=True) -> None:
def _copyto(dst, src, casting="same_kind", where: bool = True) -> None:
if _is_quantity(dst):
if _is_quantity(src):
src = src.m_as(dst.units)
Expand All @@ -619,7 +619,7 @@ def _einsum(subscripts, *operands, **kwargs):


@implements("isin", "function")
def _isin(element, test_elements, assume_unique: bool=False, invert: bool=False):
def _isin(element, test_elements, assume_unique: bool = False, invert: bool = False):
if not _is_quantity(element):
raise ValueError(
"Cannot test if unit-aware elements are in not-unit-aware array"
Expand Down Expand Up @@ -815,7 +815,9 @@ def implementation(a, b, **kwargs):
# Implement simple matching-unit or stripped-unit functions based on signature


def implement_consistent_units_by_argument(func_str, unit_arguments, wrap_output: bool=True) -> None:
def implement_consistent_units_by_argument(
func_str, unit_arguments, wrap_output: bool = True
) -> None:
# If NumPy is not available, do not attempt implement that which does not exist
if np is None:
return
Expand Down
2 changes: 1 addition & 1 deletion pint/facets/plain/qto.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _get_reduced_units(
if unit1 != unit2:
power = quantity._REGISTRY._get_dimensionality_ratio(unit1, unit2)
if power:
units = units.add(unit2, exp / power).remove([unit1])
units = units.add(unit2, exp / power).remove([unit1]) # type: ignore# exponent type
break
return units

Expand Down
36 changes: 23 additions & 13 deletions pint/facets/plain/quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ def ndim(self) -> int:
return 0
if str(type(self.magnitude)) == "NAType":
return 0
return self.magnitude.ndim
if hasattr(self.magnitude, "ndim"):
return self.magnitude.ndim
return 0

@property
def force_ndarray(self) -> bool:
Expand All @@ -162,7 +164,7 @@ def __reduce__(self) -> tuple[type, Magnitude, UnitsContainer]:
# Note: type(self) would be a mistake as subclasses built by
# dinamically can't be pickled
# TODO: Check if this is still the case.
return _unpickle_quantity, (PlainQuantity, self.magnitude, self._units)
return _unpickle_quantity, (PlainQuantity, self.magnitude, self._units) # type: ignore

@overload
def __new__(
Expand Down Expand Up @@ -239,7 +241,7 @@ def __iter__(self: PlainQuantity[MagnitudeT]) -> Iterator[Any]:
# Make sure that, if self.magnitude is not iterable, we raise TypeError as soon
# as one calls iter(self) without waiting for the first element to be drawn from
# the iterator
it_magnitude = iter(self.magnitude)
it_magnitude = iter(self.magnitude) # type: ignore[arg-type]# magnitude may not be iterable

def it_outer():
for element in it_magnitude:
Expand Down Expand Up @@ -419,7 +421,7 @@ def from_sequence(
a[i] = seq_i.m_as(units)
# raises DimensionalityError if incompatible units are used in the sequence

return cls(a, units)
return cls(a, units) # type: ignore[arg-type]

@classmethod
def from_tuple(cls, tup):
Expand Down Expand Up @@ -835,14 +837,22 @@ def __iadd__(self, other: datetime.datetime) -> datetime.timedelta: # type: ign
def __iadd__(self, other) -> PlainQuantity[MagnitudeT]:
...

def __iadd__(self, other):
def __iadd__(self, other): # type: ignore[misc]
if isinstance(other, datetime.datetime):
return self.to_timedelta() + other
elif is_duck_array_type(type(self._magnitude)):
return self._iadd_sub(other, operator.iadd)

return self._add_sub(other, operator.add)

@overload
def __add__(self, other: datetime.datetime) -> datetime.timedelta: # type: ignore[misc]
...

@overload
def __add__(self, other) -> PlainQuantity[MagnitudeT]:
...

def __add__(self, other):
if isinstance(other, datetime.datetime):
return self.to_timedelta() + other
Expand Down Expand Up @@ -1066,7 +1076,7 @@ def __rtruediv__(self, other):
__rdiv__ = __rtruediv__
__idiv__ = __itruediv__

def __ifloordiv__(self, other):
def __ifloordiv__(self, other): # type: ignore[misc]
if self._check(other):
self._magnitude //= other.to(self._units)._magnitude
elif self.dimensionless:
Expand Down Expand Up @@ -1216,7 +1226,7 @@ def __pow__(self, other) -> PlainQuantity[MagnitudeT]:
except TypeError:
return NotImplemented
else:
if not self._ok_for_muldiv:
if not self._ok_for_muldiv: # type: ignore[truthy-function]
raise OffsetUnitCalculusError(self._units)

if is_duck_array_type(type(getattr(other, "_magnitude", other))):
Expand Down Expand Up @@ -1270,7 +1280,7 @@ def __pow__(self, other) -> PlainQuantity[MagnitudeT]:
units = new_self._units**exponent

magnitude = new_self._magnitude**exponent
return self.__class__(magnitude, units)
return self.__class__(magnitude, units) # type: ignore# calling __new__ with Any

@check_implemented
def __rpow__(self, other) -> PlainQuantity[MagnitudeT]:
Expand All @@ -1287,16 +1297,16 @@ def __rpow__(self, other) -> PlainQuantity[MagnitudeT]:
return other**new_self._magnitude

def __abs__(self) -> PlainQuantity[MagnitudeT]:
return self.__class__(abs(self._magnitude), self._units)
return self.__class__(abs(self._magnitude), self._units) # type: ignore# calling __new__ with object

def __round__(self, ndigits: int | None = None) -> PlainQuantity[int]:
return self.__class__(round(self._magnitude, ndigits), self._units)
return self.__class__(round(self._magnitude, ndigits), self._units) # type: ignore# calling __new__ with object

def __pos__(self) -> PlainQuantity[MagnitudeT]:
return self.__class__(operator.pos(self._magnitude), self._units)
return self.__class__(operator.pos(self._magnitude), self._units) # type: ignore# calling __new__ with object

def __neg__(self) -> PlainQuantity[MagnitudeT]:
return self.__class__(operator.neg(self._magnitude), self._units)
return self.__class__(operator.neg(self._magnitude), self._units) # type: ignore# calling __new__ with object

@check_implemented
def __eq__(self, other):
Expand Down Expand Up @@ -1470,7 +1480,7 @@ def _ok_for_muldiv(self, no_offset_units=None) -> bool:
return True

def to_timedelta(self: PlainQuantity[MagnitudeT]) -> datetime.timedelta:
return datetime.timedelta(microseconds=self.to("microseconds").magnitude)
return datetime.timedelta(microseconds=float(self.to("microseconds").magnitude))

# We put this last to avoid overriding UnitsContainer
# and I do not want to rename it.
Expand Down
13 changes: 6 additions & 7 deletions pint/facets/plain/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def dimensionless(self) -> bool:
"""Return True if the PlainUnit is dimensionless; False otherwise."""
return not bool(self.dimensionality)

_dimensionality: UnitsContainer | None = None

@property
def dimensionality(self) -> UnitsContainer:
"""
Expand All @@ -88,11 +90,8 @@ def dimensionality(self) -> UnitsContainer:
dict
Dimensionality of the PlainUnit, e.g. ``{length: 1, time: -1}``
"""
try:
return self._dimensionality
except AttributeError:
dim = self._REGISTRY._get_dimensionality(self._units)
self._dimensionality = dim
if self._dimensionality is None:
self._dimensionality = self._REGISTRY._get_dimensionality(self._units)

return self._dimensionality

Expand Down Expand Up @@ -241,7 +240,7 @@ def systems(self):
out.add(sname)
return frozenset(out)

def from_(self, value, strict: bool=True, name="value"):
def from_(self, value, strict: bool = True, name="value"):
"""Converts a numerical value or quantity to this unit
Parameters
Expand All @@ -268,7 +267,7 @@ def from_(self, value, strict: bool=True, name="value"):
else:
return value * self

def m_from(self, value, strict: bool=True, name="value"):
def m_from(self, value, strict: bool = True, name="value"):
"""Converts a numerical value or quantity to this unit, then returns
the magnitude of the converted value
Expand Down
4 changes: 2 additions & 2 deletions pint/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ def __init__(
autoconvert_offset_to_baseunit: bool = False,
on_redefinition: str = "warn",
system=None,
auto_reduce_dimensions: bool=False,
autoconvert_to_preferred: bool=False,
auto_reduce_dimensions: bool = False,
autoconvert_to_preferred: bool = False,
preprocessors=None,
fmt_locale=None,
non_int_type=float,
Expand Down
2 changes: 1 addition & 1 deletion pint/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ def _repr_pretty_(self, p, cycle: bool) -> None:


def to_units_container(
unit_like: QuantityOrUnitLike, registry: UnitRegistry | None = None
unit_like: QuantityOrUnitLike | None, registry: UnitRegistry | None = None
) -> UnitsContainer:
"""Convert a unit compatible type to a UnitsContainer.
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ ignore = [
# https://mypy.readthedocs.io/en/stable/config_file.html#using-a-pyproject-toml-file
[tool.mypy]
# python_version = "3.9"
# follow_imports = "skip"
follow_imports = "silent"
ignore_missing_imports = true
files = "pint" # directory mypy should analyze
# # Directories to exclude from mypy's analysis
Expand All @@ -118,4 +118,4 @@ exclude = [
"docs",
"pint/default_en.txt",
"pint/constants_en.txt",
]
]

0 comments on commit 5aee334

Please sign in to comment.