From d4b3a7aee551f789cdb1528fc2ff66069a58f3eb Mon Sep 17 00:00:00 2001 From: Hernan Grecco Date: Sat, 29 Apr 2023 22:38:57 -0300 Subject: Run refurb --python-version 3.9 in code --- pint/delegates/base_defparser.py | 13 ++++---- pint/facets/dask/__init__.py | 4 +-- pint/facets/formatting/objects.py | 2 +- pint/facets/numpy/numpy_func.py | 50 +++++++++++++++---------------- pint/facets/numpy/quantity.py | 4 +-- pint/facets/numpy/unit.py | 4 +-- pint/facets/plain/quantity.py | 62 +++++++++++++++++++-------------------- pint/facets/plain/registry.py | 10 +++---- pint/facets/plain/unit.py | 8 ++--- pint/facets/system/registry.py | 2 +- pint/formatting.py | 4 +-- pint/matplotlib.py | 8 ++--- pint/pint_convert.py | 13 ++++---- pint/pint_eval.py | 10 +++---- pint/util.py | 14 ++++----- 15 files changed, 101 insertions(+), 107 deletions(-) diff --git a/pint/delegates/base_defparser.py b/pint/delegates/base_defparser.py index 774f404..88d9d37 100644 --- a/pint/delegates/base_defparser.py +++ b/pint/delegates/base_defparser.py @@ -84,14 +84,11 @@ def build_disk_cache_class(non_int_type: type): class ParsedProjecHeader(fc.NameByHashIter, PintHeader): @classmethod def from_parsed_project(cls, pp: fp.ParsedProject, reader_id): - tmp = [] - for stmt in pp.iter_statements(): - if isinstance(stmt, fp.BOS): - tmp.append( - stmt.content_hash.algorithm_name - + ":" - + stmt.content_hash.hexdigest - ) + tmp = ( + f"{stmt.content_hash.algorithm_name}:{stmt.content_hash.hexdigest}" + for stmt in pp.iter_statements() + if isinstance(stmt, fp.BOS) + ) return cls(tuple(tmp), reader_id) diff --git a/pint/facets/dask/__init__.py b/pint/facets/dask/__init__.py index 42fced0..e0821be 100644 --- a/pint/facets/dask/__init__.py +++ b/pint/facets/dask/__init__.py @@ -36,8 +36,8 @@ class DaskQuantity: def __dask_graph__(self): if isinstance(self._magnitude, dask_array.Array): return self._magnitude.__dask_graph__() - else: - return None + + return None def __dask_keys__(self): return self._magnitude.__dask_keys__() diff --git a/pint/facets/formatting/objects.py b/pint/facets/formatting/objects.py index 212fcb5..fa5ca83 100644 --- a/pint/facets/formatting/objects.py +++ b/pint/facets/formatting/objects.py @@ -154,7 +154,7 @@ class FormattingQuantity: obj = self.to_compact() else: obj = self - kwspec = dict(kwspec) + kwspec = kwspec.copy() if "length" in kwspec: kwspec["babel_length"] = kwspec.pop("length") diff --git a/pint/facets/numpy/numpy_func.py b/pint/facets/numpy/numpy_func.py index 0688367..e7a9b67 100644 --- a/pint/facets/numpy/numpy_func.py +++ b/pint/facets/numpy/numpy_func.py @@ -311,7 +311,7 @@ def implement_func(func_type, func_str, input_units=None, output_unit=None): return result_magnitude elif output_unit == "match_input": result_unit = first_input_units - elif output_unit in [ + elif output_unit in ( "sum", "mul", "delta", @@ -324,7 +324,7 @@ def implement_func(func_type, func_str, input_units=None, output_unit=None): "cbrt", "reciprocal", "size", - ]: + ): result_unit = get_op_output_unit( output_unit, first_input_units, tuple(chain(args, kwargs.values())) ) @@ -499,8 +499,8 @@ def _frexp(x, *args, **kwargs): def _power(x1, x2): if _is_quantity(x1): return x1**x2 - else: - return x2.__rpow__(x1) + + return x2.__rpow__(x1) @implements("add", "ufunc") @@ -535,8 +535,8 @@ def _full_like(a, fill_value, **kwargs): np.ones_like(a, **kwargs) * fill_value.m, fill_value.units, ) - else: - return np.ones_like(a, **kwargs) * fill_value + + return np.ones_like(a, **kwargs) * fill_value @implements("interp", "function") @@ -671,8 +671,8 @@ def _any(a, *args, **kwargs): # Only valid when multiplicative unit/no offset if a._is_multiplicative: return np.any(a._magnitude, *args, **kwargs) - else: - raise ValueError("Boolean value of Quantity with offset unit is ambiguous.") + + raise ValueError("Boolean value of Quantity with offset unit is ambiguous.") @implements("all", "function") @@ -725,7 +725,7 @@ def implement_prod_func(name): return registry.Quantity(result, units) -for name in ["prod", "nanprod"]: +for name in ("prod", "nanprod"): implement_prod_func(name) @@ -780,7 +780,7 @@ def implement_mul_func(func): return a.units._REGISTRY.Quantity(mag, units) -for func_str in ["cross", "dot"]: +for func_str in ("cross", "dot"): implement_mul_func(func_str) @@ -830,11 +830,11 @@ def implement_consistent_units_by_argument(func_str, unit_arguments, wrap_output # Conditionally wrap output if wrap_output: return output_wrap(ret) - else: - return ret + + return ret -for func_str, unit_arguments, wrap_output in [ +for func_str, unit_arguments, wrap_output in ( ("expand_dims", "a", True), ("squeeze", "a", True), ("rollaxis", "a", True), @@ -884,7 +884,7 @@ for func_str, unit_arguments, wrap_output in [ ("reshape", "a", True), ("allclose", ["a", "b", "atol"], False), ("intersect1d", ["ar1", "ar2"], True), -]: +): implement_consistent_units_by_argument(func_str, unit_arguments, wrap_output) @@ -914,7 +914,7 @@ def implement_atleast_nd(func_str): return output_unit._REGISTRY.Quantity(arrays_magnitude, output_unit) -for func_str in ["atleast_1d", "atleast_2d", "atleast_3d"]: +for func_str in ("atleast_1d", "atleast_2d", "atleast_3d"): implement_atleast_nd(func_str) @@ -935,24 +935,24 @@ def implement_single_dimensionless_argument_func(func_str): return a._REGISTRY.Quantity(func(a_stripped, *args, **kwargs)) -for func_str in ["cumprod", "cumproduct", "nancumprod"]: +for func_str in ("cumprod", "cumproduct", "nancumprod"): implement_single_dimensionless_argument_func(func_str) # Handle single-argument consistent unit functions -for func_str in [ +for func_str in ( "block", "hstack", "vstack", "dstack", "column_stack", "broadcast_arrays", -]: +): implement_func( "function", func_str, input_units="all_consistent", output_unit="match_input" ) # Handle functions that ignore units on input and output -for func_str in [ +for func_str in ( "size", "isreal", "iscomplex", @@ -969,19 +969,19 @@ for func_str in [ "count_nonzero", "nonzero", "result_type", -]: +): implement_func("function", func_str, input_units=None, output_unit=None) # Handle functions with output unit defined by operation -for func_str in ["std", "nanstd", "sum", "nansum", "cumsum", "nancumsum"]: +for func_str in ("std", "nanstd", "sum", "nansum", "cumsum", "nancumsum"): implement_func("function", func_str, input_units=None, output_unit="sum") -for func_str in ["diff", "ediff1d"]: +for func_str in ("diff", "ediff1d"): implement_func("function", func_str, input_units=None, output_unit="delta") -for func_str in ["gradient"]: +for func_str in ("gradient",): implement_func("function", func_str, input_units=None, output_unit="delta,div") -for func_str in ["linalg.solve"]: +for func_str in ("linalg.solve",): implement_func("function", func_str, input_units=None, output_unit="invdiv") -for func_str in ["var", "nanvar"]: +for func_str in ("var", "nanvar"): implement_func("function", func_str, input_units=None, output_unit="variance") diff --git a/pint/facets/numpy/quantity.py b/pint/facets/numpy/quantity.py index f9c1d86..410654a 100644 --- a/pint/facets/numpy/quantity.py +++ b/pint/facets/numpy/quantity.py @@ -99,8 +99,8 @@ class NumpyQuantity: if output_unit is not None: return self.__class__(value, output_unit) - else: - return value + + return value def __array__(self, t=None) -> np.ndarray: warnings.warn( diff --git a/pint/facets/numpy/unit.py b/pint/facets/numpy/unit.py index 73df59f..21b3594 100644 --- a/pint/facets/numpy/unit.py +++ b/pint/facets/numpy/unit.py @@ -38,5 +38,5 @@ class NumpyUnit: ), **kwargs, ) - else: - return NotImplemented + + return NotImplemented diff --git a/pint/facets/plain/quantity.py b/pint/facets/plain/quantity.py index df57ff0..1eaaa3d 100644 --- a/pint/facets/plain/quantity.py +++ b/pint/facets/plain/quantity.py @@ -274,15 +274,15 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] def __repr__(self) -> str: if isinstance(self._magnitude, float): return f"" - else: - return f"" + + return f"" def __hash__(self) -> int: self_base = self.to_base_units() if self_base.dimensionless: return hash(self_base.magnitude) - else: - return hash((self_base.__class__, self_base.magnitude, self_base.units)) + + return hash((self_base.__class__, self_base.magnitude, self_base.units)) @property def magnitude(self) -> _MagnitudeType: @@ -807,13 +807,13 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] preferred_units = list( {u for d, u in unit_selections.items() if d in preferred_dims} ) - preferred_units.sort(key=lambda unit: str(unit)) # for determinism + preferred_units.sort(key=str) # for determinism # and unpreferred_units are the selected units that weren't originally preferred unpreferred_units = list( {u for d, u in unit_selections.items() if d not in preferred_dims} ) - unpreferred_units.sort(key=lambda unit: str(unit)) # for determinism + unpreferred_units.sort(key=str) # for determinism # for indexability dimensions = list(dimension_set) @@ -911,10 +911,10 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] result_unit = sorting_keys[min_key] return self.to(result_unit) - else: - # for whatever reason, a solution wasn't found - # return the original quantity - return self + + # for whatever reason, a solution wasn't found + # return the original quantity + return self # Mathematical operations def __int__(self) -> int: @@ -1171,22 +1171,22 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] return self.to_timedelta() + other elif is_duck_array_type(type(self._magnitude)): return self._iadd_sub(other, operator.iadd) - else: - return self._add_sub(other, operator.add) + + return self._add_sub(other, operator.add) def __add__(self, other): if isinstance(other, datetime.datetime): return self.to_timedelta() + other - else: - return self._add_sub(other, operator.add) + + return self._add_sub(other, operator.add) __radd__ = __add__ def __isub__(self, other): if is_duck_array_type(type(self._magnitude)): return self._iadd_sub(other, operator.isub) - else: - return self._add_sub(other, operator.sub) + + return self._add_sub(other, operator.sub) def __sub__(self, other): return self._add_sub(other, operator.sub) @@ -1194,8 +1194,8 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] def __rsub__(self, other): if isinstance(other, datetime.datetime): return other - self.to_timedelta() - else: - return -self._add_sub(other, operator.sub) + + return -self._add_sub(other, operator.sub) @check_implemented @ireduce_dimensions @@ -1228,10 +1228,10 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] if not self._ok_for_muldiv(no_offset_units_self): raise OffsetUnitCalculusError(self._units, getattr(other, "units", "")) if len(offset_units_self) == 1: - if self._units[offset_units_self[0]] != 1 or magnitude_op not in [ + if self._units[offset_units_self[0]] != 1 or magnitude_op not in ( operator.mul, operator.imul, - ]: + ): raise OffsetUnitCalculusError( self._units, getattr(other, "units", "") ) @@ -1252,14 +1252,14 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] if not self._ok_for_muldiv(no_offset_units_self): raise OffsetUnitCalculusError(self._units, other._units) - elif no_offset_units_self == 1 and len(self._units) == 1: + elif no_offset_units_self == len(self._units) == 1: self.ito_root_units() no_offset_units_other = len(other._get_non_multiplicative_units()) if not other._ok_for_muldiv(no_offset_units_other): raise OffsetUnitCalculusError(self._units, other._units) - elif no_offset_units_other == 1 and len(other._units) == 1: + elif no_offset_units_other == len(other._units) == 1: other.ito_root_units() self._magnitude = magnitude_op(self._magnitude, other._magnitude) @@ -1297,10 +1297,10 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] if not self._ok_for_muldiv(no_offset_units_self): raise OffsetUnitCalculusError(self._units, getattr(other, "units", "")) if len(offset_units_self) == 1: - if self._units[offset_units_self[0]] != 1 or magnitude_op not in [ + if self._units[offset_units_self[0]] != 1 or magnitude_op not in ( operator.mul, operator.imul, - ]: + ): raise OffsetUnitCalculusError( self._units, getattr(other, "units", "") ) @@ -1325,14 +1325,14 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] if not self._ok_for_muldiv(no_offset_units_self): raise OffsetUnitCalculusError(self._units, other._units) - elif no_offset_units_self == 1 and len(self._units) == 1: + elif no_offset_units_self == len(self._units) == 1: new_self = self.to_root_units() no_offset_units_other = len(other._get_non_multiplicative_units()) if not other._ok_for_muldiv(no_offset_units_other): raise OffsetUnitCalculusError(self._units, other._units) - elif no_offset_units_other == 1 and len(other._units) == 1: + elif no_offset_units_other == len(other._units) == 1: other = other.to_root_units() magnitude = magnitude_op(new_self._magnitude, other._magnitude) @@ -1343,8 +1343,8 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] def __imul__(self, other): if is_duck_array_type(type(self._magnitude)): return self._imul_div(other, operator.imul) - else: - return self._mul_div(other, operator.mul) + + return self._mul_div(other, operator.mul) def __mul__(self, other): return self._mul_div(other, operator.mul) @@ -1367,8 +1367,8 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] def __itruediv__(self, other): if is_duck_array_type(type(self._magnitude)): return self._imul_div(other, operator.itruediv) - else: - return self._mul_div(other, operator.truediv) + + return self._mul_div(other, operator.truediv) def __truediv__(self, other): if isinstance(self.m, int) or isinstance(getattr(other, "m", None), int): @@ -1388,7 +1388,7 @@ class PlainQuantity(PrettyIPython, SharedRegistryObject, Generic[_MagnitudeType] no_offset_units_self = len(self._get_non_multiplicative_units()) if not self._ok_for_muldiv(no_offset_units_self): raise OffsetUnitCalculusError(self._units, "") - elif no_offset_units_self == 1 and len(self._units) == 1: + elif no_offset_units_self == len(self._units) == 1: self = self.to_root_units() return self.__class__(other_magnitude / self._magnitude, 1 / self._units) diff --git a/pint/facets/plain/registry.py b/pint/facets/plain/registry.py index 7eddcb5..035d151 100644 --- a/pint/facets/plain/registry.py +++ b/pint/facets/plain/registry.py @@ -198,7 +198,7 @@ class PlainRegistry(metaclass=RegistryMeta): mpl_formatter: str = "{:P}", ): #: Map a definition class to a adder methods. - self._adders = dict() + self._adders = {} self._register_definition_adders() self._init_dynamic_classes() @@ -1177,10 +1177,10 @@ class PlainRegistry(metaclass=RegistryMeta): match = match.groupdict() # Parse units - units = [] - for unit, value in match.items(): - # Construct measure by multiplying value by unit - units.append(float(value) * self.parse_expression(unit, case_sensitive)) + units = [ + float(value) * self.parse_expression(unit, case_sensitive) + for unit, value in match.items() + ] # Add to results results.append(units) diff --git a/pint/facets/plain/unit.py b/pint/facets/plain/unit.py index c8726ec..64a7d3c 100644 --- a/pint/facets/plain/unit.py +++ b/pint/facets/plain/unit.py @@ -165,8 +165,8 @@ class PlainUnit(PrettyIPython, SharedRegistryObject): return self._REGISTRY.Quantity(other, 1 / self._units) elif isinstance(other, UnitsContainer): return self.__class__(other / self._units) - else: - return NotImplemented + + return NotImplemented __div__ = __truediv__ __rdiv__ = __rtruediv__ @@ -207,8 +207,8 @@ class PlainUnit(PrettyIPython, SharedRegistryObject): return self_q.compare(other, op) elif isinstance(other, (PlainUnit, UnitsContainer, dict)): return self_q.compare(self._REGISTRY.Quantity(1, other), op) - else: - return NotImplemented + + return NotImplemented __lt__ = lambda self, other: self.compare(other, op=operator.lt) __le__ = lambda self, other: self.compare(other, op=operator.le) diff --git a/pint/facets/system/registry.py b/pint/facets/system/registry.py index 82edc03..accccb2 100644 --- a/pint/facets/system/registry.py +++ b/pint/facets/system/registry.py @@ -56,7 +56,7 @@ class SystemRegistry(GroupRegistry): self._systems: dict[str, System] = {} #: Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer) - self._base_units_cache = dict() + self._base_units_cache = {} self._default_system = system diff --git a/pint/formatting.py b/pint/formatting.py index c12000f..dcc8725 100644 --- a/pint/formatting.py +++ b/pint/formatting.py @@ -527,8 +527,8 @@ def split_format(spec, default, separate_format_defaults=True): elif not spec: mspec, uspec = default_mspec, default_uspec else: - mspec = mspec if mspec else default_mspec - uspec = uspec if uspec else default_uspec + mspec = mspec or default_mspec + uspec = uspec or default_uspec return mspec, uspec diff --git a/pint/matplotlib.py b/pint/matplotlib.py index ea88c70..25c257b 100644 --- a/pint/matplotlib.py +++ b/pint/matplotlib.py @@ -36,15 +36,15 @@ class PintConverter(matplotlib.units.ConversionInterface): """Convert :`Quantity` instances for matplotlib to use.""" if iterable(value): return [self._convert_value(v, unit, axis) for v in value] - else: - return self._convert_value(value, unit, axis) + + return self._convert_value(value, unit, axis) def _convert_value(self, value, unit, axis): """Handle converting using attached unit or falling back to axis units.""" if hasattr(value, "units"): return value.to(unit).magnitude - else: - return self._reg.Quantity(value, axis.get_units()).to(unit).magnitude + + return self._reg.Quantity(value, axis.get_units()).to(unit).magnitude @staticmethod def axisinfo(unit, axis): diff --git a/pint/pint_convert.py b/pint/pint_convert.py index 86d8a7a..bf90972 100755 --- a/pint/pint_convert.py +++ b/pint/pint_convert.py @@ -11,6 +11,7 @@ from __future__ import annotations import argparse +import contextlib import re from pint import UnitRegistry @@ -154,7 +155,7 @@ if args.unc: ), ) - ureg._root_units_cache = dict() + ureg._root_units_cache = {} ureg._build_cache() @@ -174,23 +175,21 @@ def convert(u_from, u_to=None, unc=None, factor=None): if prec_unc > 0: fmt = f".{prec_unc}uS" else: - try: + with contextlib.suppress(Exception): nq = nq.magnitude.n * nq.units - except Exception: - pass + fmt = "{:" + fmt + "} {:~P}" print(("{:} = " + fmt).format(q, nq.magnitude, nq.units)) def use_unc(num, fmt, prec_unc): unc = 0 - try: + with contextlib.suppress(Exception): if isinstance(num, uncertainties.UFloat): full = ("{:" + fmt + "}").format(num) unc = re.search(r"\+/-[0.]*([\d.]*)", full).group(1) unc = len(unc.replace(".", "")) - except Exception: - pass + return max(0, min(prec_unc, unc)) diff --git a/pint/pint_eval.py b/pint/pint_eval.py index 4b5b84c..e776d60 100644 --- a/pint/pint_eval.py +++ b/pint/pint_eval.py @@ -119,9 +119,9 @@ class EvalTreeNode: if op_text not in un_op: raise DefinitionSyntaxError('missing unary operator "%s"' % op_text) return un_op[op_text](self.left.evaluate(define_op, bin_op, un_op)) - else: - # single value - return define_op(self.left) + + # single value + return define_op(self.left) from collections.abc import Iterable @@ -204,7 +204,7 @@ def build_eval_tree( # (2 * 3 / 4) --> ((2 * 3) / 4) if op_priority[token_text] <= op_priority.get( prev_op, -1 - ) and token_text not in ["**", "^"]: + ) and token_text not in ("**", "^"): # previous operator is higher priority, so end previous binary op return result, index - 1 # get right side of binary op @@ -220,7 +220,7 @@ def build_eval_tree( tokens, op_priority, index + 1, depth + 1, "unary" ) result = EvalTreeNode(left=right, operator=current_token) - elif token_type == tokenlib.NUMBER or token_type == tokenlib.NAME: + elif token_type in (tokenlib.NUMBER, tokenlib.NAME): if result: # tokens with an implicit operation i.e. "1 kg" if op_priority[""] <= op_priority.get(prev_op, -1): diff --git a/pint/util.py b/pint/util.py index 5814463..48e2249 100644 --- a/pint/util.py +++ b/pint/util.py @@ -665,8 +665,8 @@ class ParserHelper(UnitsContainer): return self == ParserHelper.from_string(other, self._non_int_type) elif isinstance(other, Number): return self.scale == other and not len(self._d) - else: - return self.scale == 1 and super().__eq__(other) + + return self.scale == 1 and super().__eq__(other) def operate(self, items, op=operator.iadd, cleanup=True): d = udict(self._d) @@ -849,14 +849,12 @@ class PrettyIPython: def _repr_html_(self): if "~" in self.default_format: return f"{self:~H}" - else: - return f"{self:H}" + return f"{self:H}" def _repr_latex_(self): if "~" in self.default_format: return f"${self:~L}$" - else: - return f"${self:L}$" + return f"${self:L}$" def _repr_pretty_(self, p, cycle): if "~" in self.default_format: @@ -1014,7 +1012,7 @@ def sized(y) -> bool: @functools.cache def _build_type(class_name: str, bases): - return type(class_name, bases, dict()) + return type(class_name, bases, {}) def build_dependent_class(registry_class, class_name: str, attribute_name: str) -> type: @@ -1043,4 +1041,4 @@ def create_class_with_registry(registry, base_class) -> type: filling _REGISTRY class attribute with an actual instanced registry. """ - return type(base_class.__name__, tuple((base_class,)), dict(_REGISTRY=registry)) + return type(base_class.__name__, (base_class,), dict(_REGISTRY=registry)) -- cgit v1.2.1