diff --git a/bench/bench.py b/bench/bench.py index 6593376be..e7c3a97e0 100644 --- a/bench/bench.py +++ b/bench/bench.py @@ -1,6 +1,6 @@ +import copy import fnmatch import os -import copy from timeit import Timer import yaml diff --git a/docs/_themes/flask_theme_support.py b/docs/_themes/flask_theme_support.py index 0dcf53b75..64e249963 100644 --- a/docs/_themes/flask_theme_support.py +++ b/docs/_themes/flask_theme_support.py @@ -1,18 +1,18 @@ # flasky extensions. flasky pygments style based on tango style from pygments.style import Style from pygments.token import ( - Keyword, - Name, Comment, - String, Error, + Generic, + Keyword, + Literal, + Name, Number, Operator, - Generic, - Whitespace, - Punctuation, Other, - Literal, + Punctuation, + String, + Whitespace, ) diff --git a/docs/conf.py b/docs/conf.py index 2d740f327..211ff0b10 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- # # pint documentation build configuration file, created by # sphinx-quickstart on Thu Mar 1 13:33:14 2012. @@ -12,9 +11,10 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import pkg_resources import datetime +import pkg_resources + # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. @@ -60,7 +60,7 @@ try: # pragma: no cover version = pkg_resources.get_distribution(project).version -except: # pragma: no cover +except Exception: # pragma: no cover # we seem to have a local copy not installed without setuptools # so the reported version will be unknown version = "unknown" @@ -200,11 +200,11 @@ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', + # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', + # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. - "preamble": "".join(("\DeclareUnicodeCharacter{2212}{-}",)) # MINUS + "preamble": "".join((r"\DeclareUnicodeCharacter{2212}{-}",)) # MINUS } # Grouping the document tree into LaTeX files. List of tuples diff --git a/pint/__init__.py b/pint/__init__.py index 7e27f55b2..682e4e717 100644 --- a/pint/__init__.py +++ b/pint/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint ~~~~ @@ -12,6 +11,8 @@ :license: BSD, see LICENSE for more details. """ +import sys + import pkg_resources from .context import Context @@ -26,24 +27,24 @@ from .formatting import formatter from .measurement import Measurement from .quantity import Quantity -from .registry import UnitRegistry, LazyRegistry +from .registry import LazyRegistry, UnitRegistry from .unit import Unit -from .util import pi_theorem, logger - - -import sys +from .util import logger, pi_theorem try: - from pintpandas import PintType, PintArray + from pintpandas import PintArray, PintType + + del PintType + del PintArray _HAS_PINTPANDAS = True -except Exception: +except ImportError: _HAS_PINTPANDAS = False _, _pintpandas_error, _ = sys.exc_info() try: # pragma: no cover __version__ = pkg_resources.get_distribution("pint").version -except: # pragma: no cover +except Exception: # pragma: no cover # we seem to have a local copy not installed without setuptools # so the reported version will be unknown __version__ = "unknown" @@ -124,7 +125,9 @@ def test(): "RedefinitionError", "UndefinedUnitError", "UnitStrippedWarning", + "formatter", "get_application_registry", "set_application_registry", + "pi_theorem", "__version__", ) diff --git a/pint/babel_names.py b/pint/babel_names.py index e4bd1a002..9f23b8366 100644 --- a/pint/babel_names.py +++ b/pint/babel_names.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.babel ~~~~~~~~~~ @@ -57,7 +56,7 @@ millimeter="length-millimeter", metric_horsepower="power-horsepower", gibibyte="digital-gigabyte", - ## 'temperature-generic', + # 'temperature-generic', liter="volume-liter", turn="angle-revolution", microsecond="duration-microsecond", @@ -111,7 +110,7 @@ century="duration-century", cubic_foot="volume-cubic-foot", deciliter="volume-deciliter", - ##pint='volume-pint-metric', + # pint='volume-pint-metric', cubic_meter="volume-cubic-meter", cubic_kilometer="volume-cubic-kilometer", quart="volume-quart", diff --git a/pint/compat.py b/pint/compat.py index 3f7e49fb5..6f64acbfb 100644 --- a/pint/compat.py +++ b/pint/compat.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.compat ~~~~~~~~~~~ @@ -9,10 +8,9 @@ :license: BSD, see LICENSE for more details. """ import tokenize -import warnings +from decimal import Decimal from io import BytesIO from numbers import Number -from decimal import Decimal def tokenizer(input_string): @@ -129,10 +127,12 @@ def _to_magnitude(value, force_ndarray=False): HAS_BABEL = False if not HAS_BABEL: - Loc = babel_units = None + Loc = babel_units = None # noqa: F811 # Define location of pint.Quantity in NEP-13 type cast hierarchy by defining upcast and # downcast/wrappable types + + def is_upcast_type(other): # Check if class name is in preset list return other.__class__.__name__ in ("PintArray", "Series", "DataArray") diff --git a/pint/context.py b/pint/context.py index e027864b1..db57336e5 100644 --- a/pint/context.py +++ b/pint/context.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.context ~~~~~~~~~~~~ @@ -13,8 +12,8 @@ import weakref from collections import ChainMap, defaultdict -from .util import ParserHelper, UnitsContainer, to_units_container, SourceIterator from .errors import DefinitionSyntaxError +from .util import ParserHelper, SourceIterator, to_units_container #: Regex to match the header parts of a context. _header_re = re.compile( @@ -37,6 +36,7 @@ class Context: dimension to another. Each Dimension are specified using a UnitsContainer. Simple transformation are given with a function taking a single parameter. + >>> from pint.util import UnitsContainer >>> timedim = UnitsContainer({'[time]': 1}) >>> spacedim = UnitsContainer({'[length]': 1}) >>> def f(time): @@ -106,10 +106,10 @@ def from_lines(cls, lines, to_base_func=None): else: aliases = () defaults = r.groupdict()["defaults"] - except: + except Exception as exc: raise DefinitionSyntaxError( "Could not parse the Context header '%s'" % header, lineno=lineno - ) + ) from exc if defaults: @@ -123,11 +123,11 @@ def to_num(val): try: defaults = (part.split("=") for part in defaults.strip("()").split(",")) defaults = {str(k).strip(): to_num(v) for k, v in defaults} - except (ValueError, TypeError): + except (ValueError, TypeError) as exc: raise DefinitionSyntaxError( f"Could not parse Context definition defaults: '{txt}'", lineno=lineno, - ) + ) from exc ctx = cls(name, aliases, defaults) else: @@ -156,11 +156,11 @@ def to_num(val): ctx.add_transformation(src, dst, func) else: raise Exception - except: + except Exception as exc: raise DefinitionSyntaxError( "Could not parse Context %s relation '%s'" % (name, line), lineno=lineno, - ) + ) from exc if defaults: missing_pars = defaults.keys() - set(names) diff --git a/pint/converters.py b/pint/converters.py index 62572f8ad..ff1624ce3 100644 --- a/pint/converters.py +++ b/pint/converters.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.converters ~~~~~~~~~~~~~~~ diff --git a/pint/definitions.py b/pint/definitions.py index e6ad101cb..0ca7ed4fc 100644 --- a/pint/definitions.py +++ b/pint/definitions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.definitions ~~~~~~~~~~~~~~~~ @@ -9,8 +8,8 @@ :license: BSD, see LICENSE for more details. """ -from .converters import ScaleConverter, OffsetConverter -from .util import UnitsContainer, _is_dim, ParserHelper +from .converters import OffsetConverter, ScaleConverter +from .util import ParserHelper, UnitsContainer, _is_dim class Definition: diff --git a/pint/errors.py b/pint/errors.py index d5ae803f0..c0d9ab7ae 100644 --- a/pint/errors.py +++ b/pint/errors.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.errors ~~~~~~~~~~~ diff --git a/pint/formatting.py b/pint/formatting.py index 931e15414..2564030de 100644 --- a/pint/formatting.py +++ b/pint/formatting.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.formatter ~~~~~~~~~~~~~~ @@ -11,7 +10,7 @@ import re -from .babel_names import _babel_units, _babel_lengths +from .babel_names import _babel_lengths, _babel_units from .compat import Loc __JOIN_REG_EXP = re.compile(r"\{\d*\}") @@ -43,7 +42,7 @@ def _pretty_fmt_exponent(num): """Format an number into a pretty printed exponent. """ # TODO: Will not work for decimals - ret = "{0:n}".format(num).replace("-", "⁻") + ret = f"{num:n}".replace("-", "⁻") for n in range(10): ret = ret.replace(str(n), _PRETTY_EXPONENTS[n]) return ret @@ -104,7 +103,7 @@ def formatter( division_fmt=" / ", power_fmt="{} ** {}", parentheses_fmt="({0})", - exp_call=lambda x: "{0:n}".format(x), + exp_call=lambda x: f"{x:n}", locale=None, babel_length="long", babel_plural_form="one", @@ -266,7 +265,7 @@ def _tothe(power): # remove unit prefix if it exists # siunitx supports \prefix commands - l = lpos if power >= 0 else lneg + lpick = lpos if power >= 0 else lneg prefix = None for p in registry._prefixes.values(): p = str(p) @@ -275,11 +274,11 @@ def _tothe(power): unit = unit.replace(prefix, "", 1) if power < 0: - l.append(r"\per") + lpick.append(r"\per") if prefix is not None: - l.append(r"\{}".format(prefix)) - l.append(r"\{}".format(unit)) - l.append(r"{}".format(_tothe(abs(power)))) + lpick.append(r"\{}".format(prefix)) + lpick.append(r"\{}".format(unit)) + lpick.append(r"{}".format(_tothe(abs(power)))) return "".join(lpos) + "".join(lneg) diff --git a/pint/matplotlib.py b/pint/matplotlib.py index 2390677f0..3b7b0af90 100644 --- a/pint/matplotlib.py +++ b/pint/matplotlib.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.matplotlib ~~~~~~~~~~~~~~~ diff --git a/pint/measurement.py b/pint/measurement.py index 54df1d802..98ba7a575 100644 --- a/pint/measurement.py +++ b/pint/measurement.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.measurement ~~~~~~~~~~~~~~~~ @@ -76,7 +75,7 @@ def __repr__(self): ) def __str__(self): - return "{0}".format(self) + return "{}".format(self) def __format__(self, spec): # special cases diff --git a/pint/numpy_func.py b/pint/numpy_func.py index 52d791dea..75a4de6a6 100644 --- a/pint/numpy_func.py +++ b/pint/numpy_func.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.numpy_func ~~~~~~~~~~~~~~~ @@ -7,12 +6,12 @@ :license: BSD, see LICENSE for more details. """ +import warnings from inspect import signature from itertools import chain -import warnings -from .compat import NP_NO_VALUE, is_upcast_type, np, eq -from .errors import DimensionalityError, UnitStrippedWarning +from .compat import eq, is_upcast_type, np +from .errors import DimensionalityError from .util import iterable, sized HANDLED_UFUNCS = {} @@ -92,8 +91,8 @@ def convert_to_consistent_units(*args, pre_calc_units=None, **kwargs): def unwrap_and_wrap_consistent_units(*args): """Strip units from args while providing a rewrapping function. - Returns the given args as parsed by convert_to_consistent_units assuming units of first - arg with units, along with a wrapper to restore that unit to the output. + Returns the given args as parsed by convert_to_consistent_units assuming units of + first arg with units, along with a wrapper to restore that unit to the output. """ first_input_units = _get_first_input_units(args) args, _ = convert_to_consistent_units(*args, pre_calc_units=first_input_units) @@ -167,7 +166,9 @@ def get_op_output_unit(unit_op, first_input_units, all_args=[], size=None): def implements(numpy_func_string, func_type): - """Register an __array_function__/__array_ufunc__ implementation for Quantity objects.""" + """Register an __array_function__/__array_ufunc__ implementation for Quantity + objects. + """ def decorator(func): if func_type == "function": @@ -198,8 +199,8 @@ def implementation(*args, **kwargs): *args, pre_calc_units=first_input_units, **kwargs ) else: - # Match all input args/kwargs to input_units, or if input_units is None, simply - # strip units + # Match all input args/kwargs to input_units, or if input_units is None, + # simply strip units stripped_args, stripped_kwargs = convert_to_consistent_units( *args, pre_calc_units=input_units, **kwargs ) @@ -237,19 +238,19 @@ def implementation(*args, **kwargs): Define ufunc behavior collections. - `strip_unit_input_output_ufuncs`: units should be ignored on both input and output -- `matching_input_bare_output_ufuncs`: inputs are converted to matching units, but outputs are - returned as-is -- `matching_input_set_units_output_ufuncs`: inputs are converted to matching units, and the - output units are as set by the dict value -- `set_units_ufuncs`: dict values are specified as (in_unit, out_unit), so that inputs are - converted to in_unit before having magnitude passed to NumPy ufunc, and outputs are set to - have out_unit +- `matching_input_bare_output_ufuncs`: inputs are converted to matching units, but + outputs are returned as-is +- `matching_input_set_units_output_ufuncs`: inputs are converted to matching units, and + the output units are as set by the dict value +- `set_units_ufuncs`: dict values are specified as (in_unit, out_unit), so that inputs + are converted to in_unit before having magnitude passed to NumPy ufunc, and outputs + are set to have out_unit - `matching_input_copy_units_output_ufuncs`: inputs are converted to matching units, and outputs are set to that unit -- `copy_units_output_ufuncs`: input units (except the first) are ignored, and output is set to - that of the first input unit -- `op_units_output_ufuncs`: determine output unit from input unit as determined by operation - (see `get_op_output_unit`) +- `copy_units_output_ufuncs`: input units (except the first) are ignored, and output is + set to that of the first input unit +- `op_units_output_ufuncs`: determine output unit from input unit as determined by + operation (see `get_op_output_unit`) """ strip_unit_input_output_ufuncs = ["isnan", "isinf", "isfinite", "signbit"] matching_input_bare_output_ufuncs = [ @@ -289,9 +290,10 @@ def implementation(*args, **kwargs): "logaddexp": ("", ""), "logaddexp2": ("", ""), } -# TODO (#905 follow-up): while this matches previous behavior, some of these have optional -# arguments that should not be Quantities. This should be fixed, and tests using these -# optional arguments should be added. +# TODO (#905 follow-up): +# while this matches previous behavior, some of these have optional arguments that +# should not be Quantities. This should be fixed, and tests using these optional +# arguments should be added. matching_input_copy_units_output_ufuncs = [ "compress", "conj", @@ -398,9 +400,9 @@ def _power(x1, x2): def _add_subtract_handle_non_quantity_zero(x1, x2): - # As in #121/#122, if a value is 0 (but not Quantity 0) do the operation without checking - # units. We do the calculation instead of just returning the same value to enforce any - # shape checking and type casting due to the operation. + # As in #121/#122, if a value is 0 (but not Quantity 0) do the operation without + # checking units. We do the calculation instead of just returning the same value to + # enforce any shape checking and type casting due to the operation. if eq(x1, 0, True): (x2,), output_wrap = unwrap_and_wrap_consistent_units(x2) elif eq(x2, 0, True): @@ -546,8 +548,8 @@ def _isin(element, test_elements, assume_unique=False, invert=False): try: compatible_test_elements.append(test_element.m_as(element.units)) except DimensionalityError: - # Incompatible unit test elements cannot be in element, but others in sequence - # may + # Incompatible unit test elements cannot be in element, but others in + # sequence may pass test_elements = compatible_test_elements else: @@ -679,8 +681,8 @@ def implementation(*arrays): "function", func_str, input_units="all_consistent", output_unit="match_input" ) -# Handle cumulative products (which must be dimensionless for consistent units across output -# array) +# Handle cumulative products (which must be dimensionless for consistent units across +# output array) for func_str in ["cumprod", "cumproduct", "nancumprod"]: implement_func( "function", func_str, input_units="dimensionless", output_unit="match_input" diff --git a/pint/pint_eval.py b/pint/pint_eval.py index f7e08a218..afa3877f9 100644 --- a/pint/pint_eval.py +++ b/pint/pint_eval.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.pint_eval ~~~~~~~~~~~~~~ @@ -10,7 +9,6 @@ """ import operator - import token as tokenlib from .errors import DefinitionSyntaxError @@ -95,10 +93,11 @@ def build_eval_tree(tokens, op_priority=_OP_PRIORITY, index=0, depth=0, prev_op= Params: Index, depth, and prev_op used recursively, so don't touch. Tokens is an iterable of tokens from an expression to be evaluated. - - Transform the tokens from an expression into a recursive parse tree, following order of operations. - Operations can include binary ops (3 + 4), implicit ops (3 kg), or unary ops (-1). - + + Transform the tokens from an expression into a recursive parse tree, following order + of operations. Operations can include binary ops (3 + 4), implicit ops (3 kg), or + unary ops (-1). + General Strategy: 1) Get left side of operator 2) If no tokens left, return final result @@ -109,7 +108,7 @@ def build_eval_tree(tokens, op_priority=_OP_PRIORITY, index=0, depth=0, prev_op= 6) Go back to step #2 """ - if depth == 0 and prev_op == None: + if depth == 0 and prev_op is None: # ensure tokens is list so we can access by index tokens = list(tokens) @@ -147,9 +146,10 @@ def build_eval_tree(tokens, op_priority=_OP_PRIORITY, index=0, depth=0, prev_op= result = right elif token_text in op_priority: if result: - # equal-priority operators are grouped in a left-to-right order, unless they're - # exponentiation, in which case they're grouped right-to-left - # this allows us to get the expected behavior for multiple exponents + # equal-priority operators are grouped in a left-to-right order, + # unless they're exponentiation, in which case they're grouped + # right-to-left this allows us to get the expected behavior for + # multiple exponents # (2^3^4) --> (2^(3^4)) # (2 * 3 / 4) --> ((2 * 3) / 4) if op_priority[token_text] <= op_priority.get( @@ -174,7 +174,8 @@ def build_eval_tree(tokens, op_priority=_OP_PRIORITY, index=0, depth=0, prev_op= if result: # tokens with an implicit operation i.e. "1 kg" if op_priority[""] <= op_priority.get(prev_op, -1): - # previous operator is higher priority than implicit, so end previous binary op + # previous operator is higher priority than implicit, so end + # previous binary op return result, index - 1 right, index = build_eval_tree( tokens, op_priority, index, depth + 1, "" diff --git a/pint/quantity.py b/pint/quantity.py index 1aff1c238..627e3f216 100644 --- a/pint/quantity.py +++ b/pint/quantity.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.quantity ~~~~~~~~~~~~~ @@ -21,53 +20,49 @@ from pkg_resources.extern.packaging import version -from .formatting import ( - remove_custom_flags, - siunitx_format_unit, - ndarray_to_latex, - ndarray_to_latex_parts, +from .compat import SKIP_ARRAY_FUNCTION_CHANGE_WARNING # noqa: F401 +from .compat import ( + NUMPY_VER, + BehaviorChangeWarning, + Loc, + _to_magnitude, + array_function_change_msg, + eq, + is_upcast_type, + ndarray, + np, ) +from .definitions import UnitDefinition from .errors import ( DimensionalityError, OffsetUnitCalculusError, PintTypeError, - UndefinedUnitError, UnitStrippedWarning, ) -from .definitions import UnitDefinition -from .compat import ( - Loc, - NUMPY_VER, - SKIP_ARRAY_FUNCTION_CHANGE_WARNING, - BehaviorChangeWarning, - ndarray, - np, - _to_magnitude, - is_upcast_type, - eq, - array_function_change_msg, -) -from .util import ( - PrettyIPython, - logger, - UnitsContainer, - SharedRegistryObject, - to_units_container, - infer_base_unit, - iterable, - sized, +from .formatting import ( + ndarray_to_latex, + ndarray_to_latex_parts, + remove_custom_flags, + siunitx_format_unit, ) from .numpy_func import ( HANDLED_UFUNCS, copy_units_output_ufuncs, get_op_output_unit, - matching_input_bare_output_ufuncs, matching_input_copy_units_output_ufuncs, matching_input_set_units_output_ufuncs, numpy_wrap, op_units_output_ufuncs, set_units_ufuncs, ) +from .util import ( + PrettyIPython, + SharedRegistryObject, + UnitsContainer, + infer_base_unit, + logger, + to_units_container, +) class _Exception(Exception): # pragma: no cover @@ -404,7 +399,7 @@ def check(self, dimension): @classmethod def from_list(cls, quant_list, units=None): - """Transforms a list of Quantities into an numpy.array quantity. + """Transforms a list of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used. Same as from_sequence. @@ -420,7 +415,7 @@ def from_list(cls, quant_list, units=None): @classmethod def from_sequence(cls, seq, units=None): - """Transforms a sequence of Quantities into an numpy.array quantity. + """Transforms a sequence of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used. If units is not specified and sequence is empty, the unit cannot be determined @@ -616,7 +611,7 @@ def to_compact(self, unit=None): log10_scale = int(math.log10(scale)) if log10_scale == math.log10(scale): SI_prefixes[log10_scale] = prefix.name - except: + except Exception: SI_prefixes[0] = "" SI_prefixes = sorted(SI_prefixes.items()) @@ -1442,30 +1437,30 @@ def _numpy_method_wrap(self, func, *args, **kwargs): return value def clip(self, first=None, second=None, out=None, **kwargs): - min = kwargs.get("min", first) - max = kwargs.get("max", second) + minimum = kwargs.get("min", first) + maximum = kwargs.get("max", second) - if min is None and max is None: + if minimum is None and maximum is None: raise TypeError("clip() takes at least 3 arguments (2 given)") - if max is None and "min" not in kwargs: - min, max = max, min + if maximum is None and "min" not in kwargs: + minimum, maximum = maximum, minimum kwargs = {"out": out} - if min is not None: - if isinstance(min, self.__class__): - kwargs["min"] = min.to(self).magnitude + if minimum is not None: + if isinstance(minimum, self.__class__): + kwargs["min"] = minimum.to(self).magnitude elif self.dimensionless: - kwargs["min"] = min + kwargs["min"] = minimum else: raise DimensionalityError("dimensionless", self._units) - if max is not None: - if isinstance(max, self.__class__): - kwargs["max"] = max.to(self).magnitude + if maximum is not None: + if isinstance(maximum, self.__class__): + kwargs["max"] = maximum.to(self).magnitude elif self.dimensionless: - kwargs["max"] = max + kwargs["max"] = maximum else: raise DimensionalityError("dimensionless", self._units) diff --git a/pint/registry.py b/pint/registry.py index 0cb585b54..444b3631a 100644 --- a/pint/registry.py +++ b/pint/registry.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.registry ~~~~~~~~~~~~~ @@ -33,54 +32,52 @@ """ import copy -import os -import re -import math import functools import itertools -import pkg_resources +import math +import os +import re +from collections import defaultdict +from contextlib import closing, contextmanager from decimal import Decimal from fractions import Fraction -from contextlib import contextmanager, closing -from io import open, StringIO -from collections import defaultdict -from tokenize import NUMBER, NAME +from io import StringIO +from tokenize import NAME, NUMBER -from . import registry_helpers -from .context import Context, ContextChain -from .util import ( - getattr_maybe_raise, - logger, - pi_theorem, - solve_dependencies, - ParserHelper, - string_preprocessor, - find_connected_nodes, - find_shortest_path, - UnitsContainer, - _is_dim, - to_units_container, - SourceIterator, -) +import pkg_resources +from . import registry_helpers, systems from .compat import tokenizer +from .context import Context, ContextChain +from .converters import ScaleConverter from .definitions import ( + AliasDefinition, Definition, - UnitDefinition, - PrefixDefinition, DimensionDefinition, - AliasDefinition, + PrefixDefinition, + UnitDefinition, ) -from .converters import ScaleConverter from .errors import ( - DimensionalityError, - UndefinedUnitError, DefinitionSyntaxError, + DimensionalityError, RedefinitionError, + UndefinedUnitError, ) - from .pint_eval import build_eval_tree -from . import systems +from .util import ( + ParserHelper, + SourceIterator, + UnitsContainer, + _is_dim, + find_connected_nodes, + find_shortest_path, + getattr_maybe_raise, + logger, + pi_theorem, + solve_dependencies, + string_preprocessor, + to_units_container, +) _BLOCK_RE = re.compile(r" |\(") @@ -115,6 +112,7 @@ class BaseRegistry(metaclass=RegistryMeta): """Base class for all registries. Capabilities: + - Register units, prefixes, and dimensions, and their relations. - Convert between units. - Find dimensionality of a unit. @@ -123,17 +121,22 @@ class BaseRegistry(metaclass=RegistryMeta): - Parse a definition file. - Allow extending the definition file parser by registering @ directives. - :param filename: path of the units definition file to load or line iterable object. - Empty to load the default definition file. - None to leave the UnitRegistry empty. - :type filename: str or None - :param force_ndarray: convert any input, scalar or not to a numpy.ndarray. - :param on_redefinition: action to take in case a unit is redefined. - 'warn', 'raise', 'ignore' - :type on_redefinition: str - :param auto_reduce_dimensions: If True, reduce dimensionality on appropriate operations. - :param preprocessors: list of callables which are iteratively ran on any input expression - or unit string + :param filename: + path of the units definition file to load or line iterable object. Empty to load + the default definition file. None to leave the UnitRegistry empty. + :type filename: + str or None + :param force_ndarray: + convert any input, scalar or not to a numpy.ndarray. + :param on_redefinition: + action to take in case a unit is redefined: 'warn', 'raise', 'ignore' + :type on_redefinition: + str + :param auto_reduce_dimensions: + If True, reduce dimensionality on appropriate operations. + :param preprocessors: + list of callables which are iteratively ran on any input expression or unit + string """ #: Map context prefix to function @@ -167,7 +170,6 @@ def __init__( auto_reduce_dimensions=False, preprocessors=None, ): - self._register_parsers() self._init_dynamic_classes() @@ -181,7 +183,8 @@ def __init__( #: Determines if dimensionality should be reduced on appropriate operations. self.auto_reduce_dimensions = auto_reduce_dimensions - #: Map between name (string) and value (string) of defaults stored in the definitions file. + #: Map between name (string) and value (string) of defaults stored in the + #: definitions file. self._defaults = {} #: Map dimension name (string) to its definition (DimensionDefinition). @@ -191,7 +194,8 @@ def __init__( #: Might contain prefixed units. self._units = {} - #: Map unit name in lower case (string) to a set of unit names with the right case. + #: 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 = defaultdict(set) @@ -1048,9 +1052,9 @@ def _is_multiplicative(self, u): # If the unit is not in the registry might be because it is not # registered with its prefixed version. # TODO: Might be better to register them. - l = self._dedup_candidates(self.parse_unit_name(u)) + candidates = self._dedup_candidates(self.parse_unit_name(u)) try: - u = l[0][1] + u = candidates[0][1] return self._units[u].is_multiplicative except KeyError: raise UndefinedUnitError(u) diff --git a/pint/registry_helpers.py b/pint/registry_helpers.py index 9fd3f752a..07877ba4a 100644 --- a/pint/registry_helpers.py +++ b/pint/registry_helpers.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.registry_helpers ~~~~~~~~~~~~~~~~~~~~~ @@ -14,7 +13,7 @@ from itertools import zip_longest from .errors import DimensionalityError -from .util import to_units_container, UnitsContainer +from .util import UnitsContainer, to_units_container def _replace_units(original_units, values_by_name): diff --git a/pint/systems.py b/pint/systems.py index 4ae836041..35752687c 100644 --- a/pint/systems.py +++ b/pint/systems.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.systems ~~~~~~~~~~~~ @@ -11,17 +10,18 @@ import re +from pint.compat import Loc + +from .babel_names import _babel_systems from .definitions import Definition, UnitDefinition from .errors import DefinitionSyntaxError, RedefinitionError from .util import ( - to_units_container, - getattr_maybe_raise, SharedRegistryObject, SourceIterator, + getattr_maybe_raise, logger, + to_units_container, ) -from .babel_names import _babel_systems -from pint.compat import Loc class Group(SharedRegistryObject): diff --git a/pint/testsuite/__init__.py b/pint/testsuite/__init__.py index ffcfbf1a4..a1e51d92e 100644 --- a/pint/testsuite/__init__.py +++ b/pint/testsuite/__init__.py @@ -1,17 +1,14 @@ -# -*- coding: utf-8 -*- - import doctest import logging +import math import os import unittest - from contextlib import contextmanager +from logging.handlers import BufferingHandler +from pint import Quantity, UnitRegistry, logger from pint.compat import ndarray, np - -from pint import logger, UnitRegistry, Quantity from pint.testsuite.helpers import PintOutputChecker -from logging.handlers import BufferingHandler class TestHandler(BufferingHandler): @@ -43,10 +40,10 @@ def capture_log(self, level=logging.DEBUG): th.setLevel(level) logger.addHandler(th) if self._test_handler is not None: - l = len(self._test_handler.buffer) + buflen = len(self._test_handler.buffer) yield th.buffer if self._test_handler is not None: - self._test_handler.buffer = self._test_handler.buffer[:l] + self._test_handler.buffer = self._test_handler.buffer[:buflen] def setUp(self): self._test_handler = None @@ -58,9 +55,8 @@ def setUp(self): def tearDown(self): if self._test_handler is not None: buf = self._test_handler.buffer - l = len(buf) msg = "\n".join(record.get("msg", str(record)) for record in buf) - self.assertEqual(l, 0, msg="%d warnings raised.\n%s" % (l, msg)) + self.assertEqual(len(buf), 0, msg=f"{len(buf)} warnings raised.\n{msg}") class QuantityTestCase(BaseTestCase): @@ -129,7 +125,8 @@ def testsuite(): # TESTING THE DOCUMENTATION requires pyyaml, serialize, numpy and uncertainties if HAS_NUMPY and HAS_UNCERTAINTIES: try: - import yaml, serialize + import serialize # noqa: F401 + import yaml # noqa: F401 add_docs(suite) except ImportError: @@ -155,8 +152,6 @@ def run(): return test_runner.run(testsuite()) -import math - _GLOBS = { "wrapping.rst": { "pendulum_period": lambda length: 2 * math.pi * math.sqrt(length / 9.806650), diff --git a/pint/testsuite/helpers.py b/pint/testsuite/helpers.py index a6cb78ccb..5a9139146 100644 --- a/pint/testsuite/helpers.py +++ b/pint/testsuite/helpers.py @@ -1,15 +1,13 @@ -# -*- coding: utf-8 -*- - import doctest -from distutils.version import StrictVersion import re import unittest +from distutils.version import StrictVersion from ..compat import ( - HAS_NUMPY, HAS_BABEL, - HAS_UNCERTAINTIES, + HAS_NUMPY, HAS_NUMPY_ARRAY_FUNCTION, + HAS_UNCERTAINTIES, NUMPY_VER, ) @@ -106,7 +104,7 @@ def check_output(self, want, got, optionflags): try: if eval(want) == eval(got): return True - except: + except Exception: pass for regex in (_q_re, _sq_re): @@ -124,7 +122,7 @@ def check_output(self, want, got, optionflags): return False return True - except: + except Exception: pass cnt = 0 @@ -138,7 +136,7 @@ def check_output(self, want, got, optionflags): if parsed_got == parsed_want: return True - except: + except Exception: pass if cnt: diff --git a/pint/testsuite/parameterized.py b/pint/testsuite/parameterized.py index 239610501..ca0a72442 100644 --- a/pint/testsuite/parameterized.py +++ b/pint/testsuite/parameterized.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# # Adds Parameterized tests for Python's unittest module # # Code from: parameterizedtestcase, version: 0.1.0 @@ -23,11 +21,10 @@ # def test_eval(self, input, expected_output): # self.assertEqual(eval(input), expected_output) +import unittest from collections.abc import Callable from functools import wraps -import unittest - def augment_method_docstring( method, new_class_dict, classname, param_names, param_values, new_method diff --git a/pint/testsuite/test_application_registry.py b/pint/testsuite/test_application_registry.py index b0f77ebc1..923304c68 100644 --- a/pint/testsuite/test_application_registry.py +++ b/pint/testsuite/test_application_registry.py @@ -11,7 +11,6 @@ get_application_registry, set_application_registry, ) - from pint.testsuite import BaseTestCase from pint.testsuite.helpers import requires_uncertainties diff --git a/pint/testsuite/test_babel.py b/pint/testsuite/test_babel.py index 2210fe706..67bc22ed4 100644 --- a/pint/testsuite/test_babel.py +++ b/pint/testsuite/test_babel.py @@ -1,8 +1,7 @@ -# -*- coding: utf-8 -*- +import os -from pint.testsuite import helpers, BaseTestCase from pint import UnitRegistry -import os +from pint.testsuite import BaseTestCase, helpers class TestBabel(BaseTestCase): diff --git a/pint/testsuite/test_contexts.py b/pint/testsuite/test_contexts.py index 5fd6598da..1b072757f 100644 --- a/pint/testsuite/test_contexts.py +++ b/pint/testsuite/test_contexts.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - import itertools from collections import defaultdict -from pint import UnitRegistry, DefinitionSyntaxError, DimensionalityError +from pint import DefinitionSyntaxError, DimensionalityError, UnitRegistry from pint.context import Context -from pint.util import UnitsContainer from pint.testsuite import QuantityTestCase +from pint.util import UnitsContainer def add_ctxs(ureg): @@ -117,7 +115,7 @@ def test_known_context_enable(self): def test_graph(self): ureg = UnitRegistry() add_ctxs(ureg) - l = UnitsContainer({"[length]": 1.0}) + l = UnitsContainer({"[length]": 1.0}) # noqa: E741 t = UnitsContainer({"[time]": -1.0}) c = UnitsContainer({"[current]": 1.0}) @@ -156,7 +154,7 @@ def test_graph(self): def test_graph_enable(self): ureg = UnitRegistry() add_ctxs(ureg) - l = UnitsContainer({"[length]": 1.0}) + l = UnitsContainer({"[length]": 1.0}) # noqa: E741 t = UnitsContainer({"[time]": -1.0}) c = UnitsContainer({"[current]": 1.0}) @@ -224,14 +222,9 @@ def test_known_nested_context(self): def test_unknown_context(self): ureg = UnitRegistry() add_ctxs(ureg) - try: + with self.assertRaises(KeyError): with ureg.context("la"): pass - except KeyError as e: - value = True - except Exception as e: - value = False - self.assertTrue(value) self.assertFalse(ureg._active_ctx) self.assertFalse(ureg._active_ctx.graph) @@ -242,15 +235,9 @@ def test_unknown_nested_context(self): with ureg.context("lc"): x = dict(ureg._active_ctx) y = dict(ureg._active_ctx.graph) - try: + with self.assertRaises(KeyError): with ureg.context("la"): pass - except KeyError as e: - value = True - except Exception as e: - value = False - - self.assertTrue(value) self.assertEqual(x, ureg._active_ctx) self.assertEqual(y, ureg._active_ctx.graph) diff --git a/pint/testsuite/test_converters.py b/pint/testsuite/test_converters.py index 7fadc0073..061b05da8 100644 --- a/pint/testsuite/test_converters.py +++ b/pint/testsuite/test_converters.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- - import itertools from pint.compat import np -from pint.converters import ScaleConverter, OffsetConverter, Converter -from pint.testsuite import helpers, BaseTestCase +from pint.converters import Converter, OffsetConverter, ScaleConverter +from pint.testsuite import BaseTestCase, helpers class TestConverter(BaseTestCase): diff --git a/pint/testsuite/test_definitions.py b/pint/testsuite/test_definitions.py index 8f30a45c5..421bdb8d8 100644 --- a/pint/testsuite/test_definitions.py +++ b/pint/testsuite/test_definitions.py @@ -1,16 +1,13 @@ -# -*- coding: utf-8 -*- - -from pint.util import UnitsContainer -from pint.converters import ScaleConverter, OffsetConverter +from pint.converters import OffsetConverter, ScaleConverter from pint.definitions import ( + AliasDefinition, Definition, + DimensionDefinition, PrefixDefinition, UnitDefinition, - DimensionDefinition, - AliasDefinition, ) - from pint.testsuite import BaseTestCase +from pint.util import UnitsContainer class TestDefinition(BaseTestCase): diff --git a/pint/testsuite/test_errors.py b/pint/testsuite/test_errors.py index 56ae7528b..cb75dd7ca 100644 --- a/pint/testsuite/test_errors.py +++ b/pint/testsuite/test_errors.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - import pickle from pint import ( DefinitionSyntaxError, DimensionalityError, - Quantity, OffsetUnitCalculusError, + Quantity, RedefinitionError, UndefinedUnitError, UnitRegistry, diff --git a/pint/testsuite/test_formatter.py b/pint/testsuite/test_formatter.py index cf5e64b44..c4a4d5766 100644 --- a/pint/testsuite/test_formatter.py +++ b/pint/testsuite/test_formatter.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from pint import formatting as fmt from pint.testsuite import QuantityTestCase diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index b61abf595..145d0cc9b 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -1,16 +1,13 @@ -# -*- coding: utf-8 -*- - import copy import math -import unittest import pprint +import unittest from pint import DimensionalityError, UnitRegistry -from pint.unit import UnitsContainer -from pint.util import ParserHelper - from pint.compat import np from pint.testsuite import QuantityTestCase, helpers +from pint.unit import UnitsContainer +from pint.util import ParserHelper class TestIssues(QuantityTestCase): @@ -265,12 +262,7 @@ def test_issue85(self): m = 1.0 * ureg.amu va = 2.0 * ureg.k * T / m - try: - va.to_base_units() - except: - self.assertTrue( - False, "Error while trying to get base units for {}".format(va) - ) + va.to_base_units() boltmk = 1.380649e-23 * ureg.J / ureg.K vb = 2.0 * boltmk * T / m @@ -391,11 +383,11 @@ def test_issue105(self): for func in (ureg.get_name, ureg.parse_expression): val = func("meter") - self.assertRaises(AttributeError, func, "METER") + with self.assertRaises(AttributeError): + func("METER") self.assertEqual(val, func("METER", False)) def test_issue121(self): - sh = (2, 1) ureg = UnitRegistry() z, v = 0, 2.0 self.assertEqual(z + v * ureg.meter, v * ureg.meter) @@ -426,16 +418,10 @@ def test_issue121b(self): z, v = np.zeros((3, 1)), 2.0 * np.ones(sh) for x, y in ((z, v), (z, v * ureg.meter), (v * ureg.meter, z)): - try: - w = x + y - self.assertTrue(False, "ValueError not raised") - except ValueError: - pass - try: - w = x - y - self.assertTrue(False, "ValueError not raised") - except ValueError: - pass + with self.assertRaises(ValueError): + x + y + with self.assertRaises(ValueError): + x - y @helpers.requires_numpy() def test_issue127(self): @@ -512,12 +498,11 @@ def test_issue339(self): self.assertEqual(q1, q2) def test_issue354_356_370(self): - q = 1 * self.ureg.second / self.ureg.millisecond self.assertEqual( - "{0:~}".format(1 * self.ureg.second / self.ureg.millisecond), "1.0 s / ms" + "{:~}".format(1 * self.ureg.second / self.ureg.millisecond), "1.0 s / ms" ) - self.assertEqual("{0:~}".format(1 * self.ureg.count), "1 count") - self.assertEqual("{0:~}".format(1 * self.ureg("MiB")), "1 MiB") + self.assertEqual("{:~}".format(1 * self.ureg.count), "1 count") + self.assertEqual("{:~}".format(1 * self.ureg("MiB")), "1 MiB") def test_issue468(self): ureg = UnitRegistry() @@ -546,7 +531,6 @@ def test_issue483(self): np.testing.assert_array_equal(p, a ** a) def test_issue523(self): - ureg = UnitRegistry() src, dst = UnitsContainer({"meter": 1}), UnitsContainer({"degF": 1}) value = 10.0 convert = self.ureg.convert @@ -635,13 +619,13 @@ def pendulum_period(length, G=Q_(1, "standard_gravity")): print(length) return (2 * math.pi * (length / G) ** 0.5).to("s") - l = 1 * ureg.m + length = Q_(1, ureg.m) # Assume earth gravity - t = pendulum_period(l) + t = pendulum_period(length) self.assertAlmostEqual(t, Q_("2.0064092925890407 second")) # Use moon gravity moon_gravity = Q_(1.625, "m/s^2") - t = pendulum_period(l, moon_gravity) + t = pendulum_period(length, moon_gravity) self.assertAlmostEqual(t, Q_("4.928936075204336 second")) def test_issue783(self): diff --git a/pint/testsuite/test_measurement.py b/pint/testsuite/test_measurement.py index d37cf6072..ff8cbc881 100644 --- a/pint/testsuite/test_measurement.py +++ b/pint/testsuite/test_measurement.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from pint import DimensionalityError from pint.testsuite import QuantityTestCase, helpers diff --git a/pint/testsuite/test_numpy.py b/pint/testsuite/test_numpy.py index b2097bb3d..8fd39d842 100644 --- a/pint/testsuite/test_numpy.py +++ b/pint/testsuite/test_numpy.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- - import copy import operator as op import unittest -from pint import DimensionalityError, OffsetUnitCalculusError, set_application_registry +from pint import DimensionalityError, OffsetUnitCalculusError from pint.compat import np from pint.testsuite import QuantityTestCase, helpers from pint.testsuite.test_umath import TestUFuncs @@ -314,20 +312,20 @@ def test_ediff1d(self): @helpers.requires_array_function_protocol() def test_gradient(self): - l = np.gradient([[1, 1], [3, 4]] * self.ureg.m, 1 * self.ureg.J) + grad = np.gradient([[1, 1], [3, 4]] * self.ureg.m, 1 * self.ureg.J) self.assertQuantityEqual( - l[0], [[2.0, 3.0], [2.0, 3.0]] * self.ureg.m / self.ureg.J + grad[0], [[2.0, 3.0], [2.0, 3.0]] * self.ureg.m / self.ureg.J ) self.assertQuantityEqual( - l[1], [[0.0, 0.0], [1.0, 1.0]] * self.ureg.m / self.ureg.J + grad[1], [[0.0, 0.0], [1.0, 1.0]] * self.ureg.m / self.ureg.J ) - l = np.gradient(self.Q_([[1, 1], [3, 4]], self.ureg.degC), 1 * self.ureg.J) + grad = np.gradient(self.Q_([[1, 1], [3, 4]], self.ureg.degC), 1 * self.ureg.J) self.assertQuantityEqual( - l[0], [[2.0, 3.0], [2.0, 3.0]] * self.ureg.delta_degC / self.ureg.J + grad[0], [[2.0, 3.0], [2.0, 3.0]] * self.ureg.delta_degC / self.ureg.J ) self.assertQuantityEqual( - l[1], [[0.0, 0.0], [1.0, 1.0]] * self.ureg.delta_degC / self.ureg.J + grad[1], [[0.0, 0.0], [1.0, 1.0]] * self.ureg.delta_degC / self.ureg.J ) @helpers.requires_array_function_protocol() @@ -501,7 +499,7 @@ def test_compress(self): ) @helpers.requires_array_function_protocol() - def test_compress(self): + def test_compress_nep18(self): self.assertQuantityEqual( np.compress([False, True], self.q, axis=1), [[2], [4]] * self.ureg.m ) diff --git a/pint/testsuite/test_numpy_func.py b/pint/testsuite/test_numpy_func.py index 573f6a462..59f0a2c13 100644 --- a/pint/testsuite/test_numpy_func.py +++ b/pint/testsuite/test_numpy_func.py @@ -1,21 +1,18 @@ -# -*- coding: utf-8 -*- +from unittest.mock import patch import pint.numpy_func - from pint import DimensionalityError, OffsetUnitCalculusError from pint.compat import np -from pint.testsuite.test_numpy import TestNumpyMethods from pint.numpy_func import ( _is_quantity, _is_quantity_sequence, - _get_first_input_units, convert_to_consistent_units, - unwrap_and_wrap_consistent_units, get_op_output_unit, implements, numpy_wrap, + unwrap_and_wrap_consistent_units, ) -from unittest.mock import patch +from pint.testsuite.test_numpy import TestNumpyMethods class TestNumPyFuncUtils(TestNumpyMethods): diff --git a/pint/testsuite/test_pint_eval.py b/pint/testsuite/test_pint_eval.py index 0dd782970..20f9b46da 100644 --- a/pint/testsuite/test_pint_eval.py +++ b/pint/testsuite/test_pint_eval.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import unittest from pint.compat import tokenizer diff --git a/pint/testsuite/test_pitheorem.py b/pint/testsuite/test_pitheorem.py index ed6806398..40abd8c2e 100644 --- a/pint/testsuite/test_pitheorem.py +++ b/pint/testsuite/test_pitheorem.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import itertools from pint import pi_theorem diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py index 3433cade5..f54e59f3b 100644 --- a/pint/testsuite/test_quantity.py +++ b/pint/testsuite/test_quantity.py @@ -1,17 +1,15 @@ -# -*- coding: utf-8 -*- - import copy import datetime import math import operator as op import warnings +from unittest.mock import patch from pint import DimensionalityError, OffsetUnitCalculusError, UnitRegistry -from pint.unit import UnitsContainer from pint.compat import BehaviorChangeWarning, np from pint.testsuite import QuantityTestCase, helpers from pint.testsuite.parameterized import ParameterizedTestCase -from unittest.mock import patch +from pint.unit import UnitsContainer class TestQuantity(QuantityTestCase): @@ -144,7 +142,7 @@ def test_quantity_format(self): # Check the special case that prevents e.g. '3 1 / second' x = self.Q_(3, UnitsContainer(second=-1)) - self.assertEqual("{0}".format(x), "3 / second") + self.assertEqual(f"{x}", "3 / second") @helpers.requires_numpy() def test_quantity_array_format(self): @@ -189,9 +187,9 @@ def test_format_compact(self): self.assertEqual(q3.magnitude, q3b.magnitude) self.assertEqual(q3.units, q3b.units) - self.assertEqual("{0:#.1f}".format(q1), "{0}".format(q1b)) - self.assertEqual("{0:#.1f}".format(q2), "{0}".format(q2b)) - self.assertEqual("{0:#.1f}".format(q3), "{0}".format(q3b)) + self.assertEqual(f"{q1:#.1f}", f"{q1b}") + self.assertEqual(f"{q2:#.1f}", f"{q2b}") + self.assertEqual(f"{q3:#.1f}", f"{q3b}") def test_default_formatting(self): ureg = UnitRegistry() @@ -271,22 +269,24 @@ def test_to_base_units(self): ) def test_convert(self): - x = self.Q_("2*inch") - self.assertQuantityAlmostEqual(x.to("meter"), self.Q_(2.0 * 0.0254, "meter")) - x = self.Q_("2*meter") - self.assertQuantityAlmostEqual(x.to("inch"), self.Q_(2.0 / 0.0254, "inch")) - x = self.Q_("2*sidereal_second") - self.assertQuantityAlmostEqual(x.to("second"), self.Q_(1.994539133, "second")) - x = self.Q_("2.54*centimeter/second") - self.assertQuantityAlmostEqual(x.to("inch/second"), self.Q_(1, "inch/second")) - x = self.Q_("2.54*centimeter") - self.assertQuantityAlmostEqual(x.to("inch").magnitude, 1) self.assertQuantityAlmostEqual( - self.Q_(2, "second").to("millisecond").magnitude, 2000 + self.Q_("2 inch").to("meter"), self.Q_(2.0 * 0.0254, "meter") ) + self.assertQuantityAlmostEqual( + self.Q_("2 meter").to("inch"), self.Q_(2.0 / 0.0254, "inch") + ) + self.assertQuantityAlmostEqual( + self.Q_("2 sidereal_year").to("second"), self.Q_(63116297.5325, "second") + ) + self.assertQuantityAlmostEqual( + self.Q_("2.54 centimeter/second").to("inch/second"), + self.Q_("1 inch/second"), + ) + self.assertAlmostEqual(self.Q_("2.54 centimeter").to("inch").magnitude, 1) + self.assertAlmostEqual(self.Q_("2 second").to("millisecond").magnitude, 2000) @helpers.requires_numpy() - def test_convert(self): + def test_convert_numpy(self): # Conversions with single units take a different codepath than # Conversions with more than one unit. @@ -606,7 +606,7 @@ def _test_inplace(self, operator, value1, value2, expected_result, unit=None): if isinstance(expected_result, str): expected_result = self.Q_(expected_result) - if not unit is None: + if unit is not None: value1 = value1 * unit value2 = value2 * unit expected_result = expected_result * unit @@ -630,7 +630,7 @@ def _test_not_inplace(self, operator, value1, value2, expected_result, unit=None if isinstance(expected_result, str): expected_result = self.Q_(expected_result) - if not unit is None: + if unit is not None: value1 = value1 * unit value2 = value2 * unit expected_result = expected_result * unit diff --git a/pint/testsuite/test_systems.py b/pint/testsuite/test_systems.py index bff359b1a..008d299f5 100644 --- a/pint/testsuite/test_systems.py +++ b/pint/testsuite/test_systems.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from pint import UnitRegistry from pint.testsuite import QuantityTestCase @@ -67,9 +65,7 @@ def test_using1(self): lines = ["@group mygroup using group1", "meter", "second"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - - g = ureg.Group("group1") + ureg.Group("group1") grp = ureg.Group.from_lines(lines, lambda x: None) self.assertEqual(grp.name, "mygroup") self.assertEqual(grp._unit_names, {"meter", "second"}) @@ -80,8 +76,6 @@ def test_using2(self): lines = ["@group mygroup using group1,group2", "meter", "second"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - ureg.Group("group1") ureg.Group("group2") grp = ureg.Group.from_lines(lines, lambda x: None) @@ -94,8 +88,6 @@ def test_spaces(self): lines = ["@group mygroup using group1 , group2", " meter ", " second "] ureg, root = self._build_empty_reg_root() - d = ureg._groups - ureg.Group("group1") ureg.Group("group2") grp = ureg.Group.from_lines(lines, lambda x: None) @@ -108,9 +100,7 @@ def test_invalidate_members(self): lines = ["@group mygroup using group1", "meter", "second"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - - g1 = ureg.Group("group1") + ureg.Group("group1") grp = ureg.Group.from_lines(lines, lambda x: None) self.assertIs(root._computed_members, None) self.assertIs(grp._computed_members, None) @@ -138,20 +128,16 @@ def define(ud): defs.append(ud.name) ureg, root = self._build_empty_reg_root() - d = ureg._groups - - grp = ureg.Group.from_lines(lines, define) + ureg.Group.from_lines(lines, define) self.assertEqual(["kings_leg", "kings_head"], defs) def test_members_including(self): - ureg, root = self._build_empty_reg_root() - d = ureg._groups g1 = ureg.Group("group1") - g1.add_units("second", "inch") + g2 = ureg.Group("group2") g2.add_units("second", "newton") @@ -185,8 +171,6 @@ def test_implicit_root(self): lines = ["@system mks", "meter", "kilogram", "second"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - s = ureg.System.from_lines(lines, lambda x: x) s._used_groups = {"root"} @@ -194,8 +178,6 @@ def test_simple_using(self): lines = ["@system mks using g1", "meter", "kilogram", "second"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - s = ureg.System.from_lines(lines, lambda x: x) s._used_groups = {"root", "g1"} @@ -203,8 +185,6 @@ def test_members_group(self): lines = ["@system mk", "meter", "kilogram"] ureg, root = self._build_empty_reg_root() - d = ureg._groups - root.add_units("second") s = ureg.System.from_lines(lines, lambda x: x) self.assertEqual(s.members, frozenset(["second"])) @@ -221,13 +201,12 @@ def test_get_compatible_units(self): lines = ["@system %s using test-imperial" % sysname, "inch"] - s = ureg.System.from_lines(lines, lambda x: x) + ureg.System.from_lines(lines, lambda x: x) c = ureg.get_compatible_units("meter", sysname) self.assertEqual(c, frozenset([ureg.inch, ureg.yard])) def test_get_base_units(self): sysname = "mysys2" - ureg = UnitRegistry() g = ureg.get_group("test-imperial") @@ -249,12 +228,11 @@ def test_get_base_units(self): def test_get_base_units_different_exponent(self): sysname = "mysys3" - ureg = UnitRegistry() g = ureg.get_group("test-imperial") g.add_units("inch", "yard", "pint") - c = ureg.get_compatible_units("meter", "test-imperial") + ureg.get_compatible_units("meter", "test-imperial") lines = ["@system %s using test-imperial" % sysname, "pint:meter"] @@ -280,7 +258,6 @@ def test_get_base_units_different_exponent(self): def test_get_base_units_relation(self): sysname = "mysys4" - ureg = UnitRegistry() g = ureg.get_group("test-imperial") @@ -302,4 +279,4 @@ def test_get_base_units_relation(self): def test_members_nowarning(self): ureg = self.ureg for name in dir(ureg.sys): - s = dir(getattr(ureg.sys, name)) + dir(getattr(ureg.sys, name)) diff --git a/pint/testsuite/test_umath.py b/pint/testsuite/test_umath.py index 7b917ae88..a1accc3ac 100644 --- a/pint/testsuite/test_umath.py +++ b/pint/testsuite/test_umath.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from pint import DimensionalityError from pint.compat import np from pint.testsuite import QuantityTestCase, helpers @@ -442,7 +440,6 @@ def test_arcsin(self): ) def test_arccos(self): - x = np.arange(0, 0.9, 0.1) * self.ureg.m self._test1( np.arccos, ( diff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py index e1bcf57e5..16b8929d3 100644 --- a/pint/testsuite/test_unit.py +++ b/pint/testsuite/test_unit.py @@ -1,21 +1,19 @@ -# -*- coding: utf-8 -*- - import copy import functools import math import re -from pint.compat import np -from pint.registry import UnitRegistry, LazyRegistry from pint import ( DefinitionSyntaxError, DimensionalityError, RedefinitionError, UndefinedUnitError, ) +from pint.compat import np +from pint.registry import LazyRegistry, UnitRegistry from pint.testsuite import QuantityTestCase, helpers from pint.testsuite.parameterized import ParameterizedTestCase -from pint.util import UnitsContainer, ParserHelper +from pint.util import ParserHelper, UnitsContainer class TestUnit(QuantityTestCase): @@ -84,12 +82,12 @@ def test_unit_formatting_snake_case(self): for spec, result in ( ("L", r"\mathrm{oil\_barrel}"), ("P", "oil_barrel"), - ("H", "oil\_barrel"), + ("H", r"oil\_barrel"), ("C", "oil_barrel"), ("~", "oil_bbl"), ("L~", r"\mathrm{oil\_bbl}"), ("P~", "oil_bbl"), - ("H~", "oil\_bbl"), + ("H~", r"oil\_bbl"), ("C~", "oil_bbl"), ): with self.subTest(spec): @@ -212,7 +210,7 @@ def test_base(self): ureg.define("meter = [length]") self.assertRaises(DefinitionSyntaxError, ureg.define, "meter = [length]") self.assertRaises(TypeError, ureg.define, list()) - x = ureg.define("degC = kelvin; offset: 273.15") + ureg.define("degC = kelvin; offset: 273.15") def test_define(self): ureg = UnitRegistry(None) @@ -234,10 +232,10 @@ def test_load(self): def test_default_format(self): ureg = UnitRegistry() q = ureg.meter - s1 = "{0}".format(q) - s2 = "{0:~}".format(q) + s1 = f"{q}" + s2 = f"{q:~}" ureg.default_format = "~" - s3 = "{0}".format(q) + s3 = f"{q}" self.assertEqual(s2, s3) self.assertNotEqual(s1, s3) self.assertEqual(ureg.default_format, "~") @@ -272,7 +270,6 @@ def test_parse_prefix(self): self.ureg.parse_expression("kilometer"), self.Q_(1, UnitsContainer(kilometer=1.0)), ) - # self.assertEqual(self.ureg._units['kilometer'], self.Q_(1000., UnitsContainer(meter=1.))) def test_parse_complex(self): self.assertEqual( @@ -427,11 +424,8 @@ def test_imperial_symbol(self): self.assertEqual(self.ureg.get_symbol("international_inch"), "in") def test_pint(self): - p = self.ureg.pint - l = self.ureg.liter - ip = self.ureg.imperial_pint - self.assertLess(p, l) - self.assertLess(p, ip) + self.assertLess(self.ureg.pint, self.ureg.liter) + self.assertLess(self.ureg.pint, self.ureg.imperial_pint) def test_wraps(self): def func(x): @@ -742,7 +736,7 @@ def test_lazy(self): x.test = "test" self.assertIsInstance(x, UnitRegistry) y = LazyRegistry() - q = y("meter") + y("meter") self.assertIsInstance(y, UnitRegistry) def test_redefinition(self): diff --git a/pint/testsuite/test_util.py b/pint/testsuite/test_util.py index 2d2ccd12e..d27a4ebe2 100644 --- a/pint/testsuite/test_util.py +++ b/pint/testsuite/test_util.py @@ -1,22 +1,21 @@ -# -*- coding: utf-8 -*- - import collections import copy import operator as op from decimal import Decimal + from pint.testsuite import BaseTestCase, QuantityTestCase from pint.util import ( - string_preprocessor, - find_shortest_path, - matrix_to_string, - transpose, - tokenizer, - find_connected_nodes, ParserHelper, UnitsContainer, - to_units_container, + find_connected_nodes, + find_shortest_path, iterable, + matrix_to_string, sized, + string_preprocessor, + to_units_container, + tokenizer, + transpose, ) @@ -207,7 +206,7 @@ def test_eval_token(self): class TestStringProcessor(BaseTestCase): def _test(self, bef, aft): - for pattern in ("{0}", "+{0}+"): + for pattern in ("{}", "+{}+"): b = pattern.format(bef) a = pattern.format(aft) self.assertEqual(string_preprocessor(b), a) @@ -309,7 +308,7 @@ def test_matrix_to_string(self): [[1, 2], [3, 4]], row_headers=None, col_headers=None, - fmtfun=lambda x: "{0:.2f}".format(x), + fmtfun=lambda x: f"{x:.2f}", ), "1.00\t2.00\n" "3.00\t4.00", ) diff --git a/pint/unit.py b/pint/unit.py index f96e549ff..c64f96694 100644 --- a/pint/unit.py +++ b/pint/unit.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.unit ~~~~~~~~~ @@ -14,11 +13,10 @@ import operator from numbers import Number -from .util import PrettyIPython, UnitsContainer, SharedRegistryObject - from .compat import NUMERIC_TYPES -from .formatting import siunitx_format_unit from .definitions import UnitDefinition +from .formatting import siunitx_format_unit +from .util import PrettyIPython, SharedRegistryObject, UnitsContainer class Unit(PrettyIPython, SharedRegistryObject): diff --git a/pint/util.py b/pint/util.py index d20778e22..3b6c4672b 100644 --- a/pint/util.py +++ b/pint/util.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ pint.util ~~~~~~~~~ @@ -10,20 +9,20 @@ """ import logging -from logging import NullHandler import operator import re from collections.abc import Mapping from decimal import Decimal -from numbers import Number from fractions import Fraction from functools import lru_cache +from logging import NullHandler +from numbers import Number from token import NAME, NUMBER -from .compat import tokenizer, NUMERIC_TYPES +from .compat import NUMERIC_TYPES, tokenizer +from .errors import DefinitionSyntaxError from .formatting import format_unit from .pint_eval import build_eval_tree -from .errors import DefinitionSyntaxError logger = logging.getLogger(__name__) logger.addHandler(NullHandler()) @@ -82,8 +81,10 @@ def column_echelon_form(matrix, ntype=Fraction, transpose_result=False): new_M.append(r) M = new_M - # M = [[ntype(x) for x in row] for row in M] - I = [[ntype(1) if n == nc else ntype(0) for nc in range(rows)] for n in range(rows)] + # M = [[ntype(x) for x in row] for row in M] + I = [ # noqa: E741 + [ntype(1) if n == nc else ntype(0) for nc in range(rows)] for n in range(rows) + ] swapped = [] for r in range(rows): @@ -215,7 +216,7 @@ def find_shortest_path(graph, start, end, path=None): path = (path or []) + [start] if start == end: return path - if not start in graph: + if start not in graph: return None shortest = None for node in graph[start]: @@ -228,7 +229,7 @@ def find_shortest_path(graph, start, end, path=None): def find_connected_nodes(graph, start, visited=None): - if not start in graph: + if start not in graph: return None visited = visited or set() diff --git a/setup.cfg b/setup.cfg index 6499fe786..b2de1ede9 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,3 +5,27 @@ ignore = [bdist_wheel] universal = 1 + +[flake8] +ignore= + # whitespace before ':' - doesn't work well with black + E203 + E402 + # line too long - let black worry about that + E501 + # do not assign a lambda expression, use a def + E731 + # line break before binary operator + W503 +exclude= + build + + +[isort] +default_section=THIRDPARTY +known_first_party=pint +multi_line_output=3 +include_trailing_comma=True +force_grid_wrap=0 +use_parentheses=True +line_length=88