diff --git a/cf_units/__init__.py b/cf_units/__init__.py index 33366729..f5c32263 100644 --- a/cf_units/__init__.py +++ b/cf_units/__init__.py @@ -568,9 +568,7 @@ def _ud_value_error(ud_err, message): if ud_msg: message = "{}: {}".format(message, ud_msg) - message = "[{status}] {message}".format( - status=ud_err.status_msg(), message=message - ) + message = "[{status}] {message}".format(status=ud_err.status_msg(), message=message) return ValueError(message) @@ -613,14 +611,10 @@ def __lt__(self, other): # Prevent attribute updates def __setattr__(self, name, value): - raise AttributeError( - "Instances of %s are immutable" % type(self).__name__ - ) + raise AttributeError("Instances of %s are immutable" % type(self).__name__) def __delattr__(self, name): - raise AttributeError( - "Instances of %s are immutable" % type(self).__name__ - ) + raise AttributeError("Instances of %s are immutable" % type(self).__name__) # Declare the attribute names relevant to the ordered and hashable # behaviour. @@ -753,9 +747,7 @@ def __init__(self, unit, calendar=None): ) @classmethod - def _new_from_existing_ut( - cls, category, ut_unit, calendar=None, origin=None - ): + def _new_from_existing_ut(cls, category, ut_unit, calendar=None, origin=None): # Short-circuit __init__ if we know what we are doing and already # have a UT handle. unit = cls.__new__(cls) @@ -903,9 +895,7 @@ def is_long_time_interval(self): result = False long_time_intervals = ["year", "month"] if self.is_time_reference(): - result = any( - interval in self.origin for interval in long_time_intervals - ) + result = any(interval in self.origin for interval in long_time_intervals) return result def title(self, value): @@ -1113,9 +1103,7 @@ def format(self, option=None): option = [option] for i in option: bitmask |= i - encoding = bitmask & ( - UT_ASCII | UT_ISO_8859_1 | UT_LATIN1 | UT_UTF8 - ) + encoding = bitmask & (UT_ASCII | UT_ISO_8859_1 | UT_LATIN1 | UT_UTF8) encoding_str = _encoding_lookup[encoding] result = _ud.format(self.ut_unit, bitmask) @@ -1221,9 +1209,7 @@ def offset_by_time(self, origin): """ if not isinstance(origin, (float, (int,))): - raise TypeError( - "a numeric type for the origin argument is" " required" - ) + raise TypeError("a numeric type for the origin argument is" " required") try: ut_unit = _ud.offset_by_time(self.ut_unit, origin) except _ud.UdunitsError as exception: @@ -1304,9 +1290,7 @@ def root(self, root): ) raise value_error from None calendar = None - result = Unit._new_from_existing_ut( - _CATEGORY_UDUNIT, ut_unit, calendar - ) + result = Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit, calendar) return result def log(self, base): @@ -1337,20 +1321,15 @@ def log(self, base): try: ut_unit = _ud.log(base, self.ut_unit) except TypeError: - raise TypeError( - "A numeric type for the base argument is " " required" - ) + raise TypeError("A numeric type for the base argument is " " required") except _ud.UdunitsError as exception: value_err = _ud_value_error( exception, - "Failed to calculate logorithmic base " - "of {!r}".format(self), + "Failed to calculate logorithmic base " "of {!r}".format(self), ) raise value_err from None calendar = None - result = Unit._new_from_existing_ut( - _CATEGORY_UDUNIT, ut_unit, calendar - ) + result = Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit, calendar) return result def __str__(self): @@ -1444,9 +1423,7 @@ def _op_common(self, other, op_func): ) raise value_err from None calendar = None - result = Unit._new_from_existing_ut( - _CATEGORY_UDUNIT, ut_unit, calendar - ) + result = Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit, calendar) return result def __rmul__(self, other): @@ -1561,9 +1538,7 @@ def __pow__(self, power): try: power = float(power) except ValueError: - raise TypeError( - "A numeric value is required for the power" " argument." - ) + raise TypeError("A numeric value is required for the power" " argument.") if self.is_unknown(): result = self @@ -1759,16 +1734,14 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False): result = cftime.date2num( result_datetimes, other.cftime_unit, other.calendar ) - convert_type = isinstance( - value, np.ndarray - ) and np.issubsctype(value.dtype, np.floating) + convert_type = isinstance(value, np.ndarray) and np.issubsctype( + value.dtype, np.floating + ) if convert_type: result = result.astype(value.dtype) else: try: - ut_converter = _ud.get_converter( - self.ut_unit, other.ut_unit - ) + ut_converter = _ud.get_converter(self.ut_unit, other.ut_unit) except _ud.UdunitsError as exception: value_err = _ud_value_error( exception, @@ -1796,8 +1769,7 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False): # Strict type check of numpy array. if result.dtype.type not in (np.float32, np.float64): raise TypeError( - "Expect a numpy array of '%s' or '%s'" - % np.float32, + "Expect a numpy array of '%s' or '%s'" % np.float32, np.float64, ) ctype = result.dtype.type @@ -1805,15 +1777,11 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False): # _cv_convert_array to convert our array in 1d form result_tmp = result.ravel(order="A") # Do the actual conversion. - _cv_convert_array[ctype]( - ut_converter, result_tmp, result_tmp - ) + _cv_convert_array[ctype](ut_converter, result_tmp, result_tmp) # If result_tmp was a copy, not a view (i.e. not C # contiguous), copy the data back to the original. if not np.shares_memory(result, result_tmp): - result_tmp = result_tmp.reshape( - result.shape, order="A" - ) + result_tmp = result_tmp.reshape(result.shape, order="A") if isinstance(result, np.ma.MaskedArray): result.data[...] = result_tmp else: @@ -1829,9 +1797,7 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False): result = _cv_convert_scalar[ctype](ut_converter, result) return result else: - raise ValueError( - "Unable to convert from '%r' to '%r'." % (self, other) - ) + raise ValueError("Unable to convert from '%r' to '%r'." % (self, other)) @property def cftime_unit(self): diff --git a/cf_units/_udunits2_parser/__init__.py b/cf_units/_udunits2_parser/__init__.py index 0c7c0111..a669e00e 100644 --- a/cf_units/_udunits2_parser/__init__.py +++ b/cf_units/_udunits2_parser/__init__.py @@ -15,8 +15,7 @@ # Dictionary mapping token rule id to token name. TOKEN_ID_NAMES = { - getattr(udunits2Lexer, rule, None): rule - for rule in udunits2Lexer.ruleNames + getattr(udunits2Lexer, rule, None): rule for rule in udunits2Lexer.ruleNames } diff --git a/cf_units/_udunits2_parser/compile.py b/cf_units/_udunits2_parser/compile.py index b52719c4..24f7c67f 100644 --- a/cf_units/_udunits2_parser/compile.py +++ b/cf_units/_udunits2_parser/compile.py @@ -44,9 +44,7 @@ def expand_lexer(source, target): with open(source, "r") as fh: content = fh.read() - template = jinja2.Environment(loader=jinja2.BaseLoader).from_string( - content - ) + template = jinja2.Environment(loader=jinja2.BaseLoader).from_string(content) current_mode = "DEFAULT_MODE" diff --git a/cf_units/_udunits2_parser/parser/udunits2Lexer.py b/cf_units/_udunits2_parser/parser/udunits2Lexer.py index 320d5b63..3d4c33df 100644 --- a/cf_units/_udunits2_parser/parser/udunits2Lexer.py +++ b/cf_units/_udunits2_parser/parser/udunits2Lexer.py @@ -1,6 +1,5 @@ # Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/parser/udunits2Lexer.g4 by ANTLR 4.11.1 import sys -from io import StringIO from antlr4 import * diff --git a/cf_units/_udunits2_parser/parser/udunits2Parser.py b/cf_units/_udunits2_parser/parser/udunits2Parser.py index ee6d6d1f..30aa96ce 100644 --- a/cf_units/_udunits2_parser/parser/udunits2Parser.py +++ b/cf_units/_udunits2_parser/parser/udunits2Parser.py @@ -1,7 +1,6 @@ # Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/udunits2Parser.g4 by ANTLR 4.11.1 # encoding: utf-8 import sys -from io import StringIO from antlr4 import * @@ -1384,9 +1383,7 @@ def EOF(self): return self.getToken(udunits2Parser.EOF, 0) def shift_spec(self): - return self.getTypedRuleContext( - udunits2Parser.Shift_specContext, 0 - ) + return self.getTypedRuleContext(udunits2Parser.Shift_specContext, 0) def getRuleIndex(self): return udunits2Parser.RULE_unit_spec @@ -1460,9 +1457,7 @@ def accept(self, visitor: ParseTreeVisitor): return visitor.visitChildren(self) def shift_spec(self): - localctx = udunits2Parser.Shift_specContext( - self, self._ctx, self.state - ) + localctx = udunits2Parser.Shift_specContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_shift_spec) self._la = 0 # Token type try: @@ -1593,9 +1588,7 @@ def product(self, _p: int = 0): _prevctx = localctx self.state = 66 self._errHandler.sync(self) - la_ = self._interp.adaptivePredict( - self._input, 7, self._ctx - ) + la_ = self._interp.adaptivePredict(self._input, 7, self._ctx) if la_ == 1: localctx = udunits2Parser.ProductContext( self, _parentctx, _parentState @@ -1717,9 +1710,7 @@ def __init__( self.parser = parser def basic_spec(self): - return self.getTypedRuleContext( - udunits2Parser.Basic_specContext, 0 - ) + return self.getTypedRuleContext(udunits2Parser.Basic_specContext, 0) def integer(self): return self.getTypedRuleContext(udunits2Parser.IntegerContext, 0) @@ -1805,9 +1796,7 @@ def OPEN_PAREN(self): return self.getToken(udunits2Parser.OPEN_PAREN, 0) def shift_spec(self): - return self.getTypedRuleContext( - udunits2Parser.Shift_specContext, 0 - ) + return self.getTypedRuleContext(udunits2Parser.Shift_specContext, 0) def CLOSE_PAREN(self): return self.getToken(udunits2Parser.CLOSE_PAREN, 0) @@ -1825,9 +1814,7 @@ def accept(self, visitor: ParseTreeVisitor): return visitor.visitChildren(self) def basic_spec(self): - localctx = udunits2Parser.Basic_specContext( - self, self._ctx, self.state - ) + localctx = udunits2Parser.Basic_specContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_basic_spec) try: self.state = 90 @@ -1985,9 +1972,7 @@ def INT(self): return self.getToken(udunits2Parser.INT, 0) def signed_clock(self): - return self.getTypedRuleContext( - udunits2Parser.Signed_clockContext, 0 - ) + return self.getTypedRuleContext(udunits2Parser.Signed_clockContext, 0) def WS(self, i: int = None): if i is None: @@ -1996,9 +1981,7 @@ def WS(self, i: int = None): return self.getToken(udunits2Parser.WS, i) def timezone_offset(self): - return self.getTypedRuleContext( - udunits2Parser.Timezone_offsetContext, 0 - ) + return self.getTypedRuleContext(udunits2Parser.Timezone_offsetContext, 0) def DT_T_CLOCK(self): return self.getToken(udunits2Parser.DT_T_CLOCK, 0) @@ -2133,9 +2116,7 @@ def accept(self, visitor: ParseTreeVisitor): return visitor.visitChildren(self) def signed_clock(self): - localctx = udunits2Parser.Signed_clockContext( - self, self._ctx, self.state - ) + localctx = udunits2Parser.Signed_clockContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_signed_clock) try: self.state = 123 @@ -2195,9 +2176,7 @@ def accept(self, visitor: ParseTreeVisitor): return visitor.visitChildren(self) def timezone_offset(self): - localctx = udunits2Parser.Timezone_offsetContext( - self, self._ctx, self.state - ) + localctx = udunits2Parser.Timezone_offsetContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_timezone_offset) try: self.state = 127 diff --git a/cf_units/tests/integration/parse/test_parse.py b/cf_units/tests/integration/parse/test_parse.py index d42b7a36..4bceebde 100644 --- a/cf_units/tests/integration/parse/test_parse.py +++ b/cf_units/tests/integration/parse/test_parse.py @@ -167,9 +167,9 @@ def test_invalid_units(_, unit_str): cf_valid = False # Double check that udunits2 can't parse this. - assert ( - cf_valid is False - ), "Unit {!r} is unexpectedly valid in UDUNITS2".format(unit_str) + assert cf_valid is False, "Unit {!r} is unexpectedly valid in UDUNITS2".format( + unit_str + ) try: normalize(unit_str) @@ -234,9 +234,7 @@ def test_invalid_in_udunits_but_still_parses(_, unit_str, expected): ] -@pytest.mark.parametrize( - "_, unit_str, expected", multi_enumerate(known_issues) -) +@pytest.mark.parametrize("_, unit_str, expected", multi_enumerate(known_issues)) def test_known_issues(_, unit_str, expected): # Unfortunately the grammar is not perfect. # These are the cases that don't work yet but which do work with udunits. diff --git a/cf_units/tests/integration/test__Unit_date2num.py b/cf_units/tests/integration/test__Unit_date2num.py index 32cbcff8..c724d20e 100644 --- a/cf_units/tests/integration/test__Unit_date2num.py +++ b/cf_units/tests/integration/test__Unit_date2num.py @@ -4,7 +4,6 @@ # See LICENSE in the root of the repository for full licensing details. """Test method :meth:`cf_units.Unit.date2num`.""" - import cftime import pytest diff --git a/cf_units/tests/integration/test__Unit_num2date.py b/cf_units/tests/integration/test__Unit_num2date.py index 11d4c1c3..d39c0ad0 100644 --- a/cf_units/tests/integration/test__Unit_num2date.py +++ b/cf_units/tests/integration/test__Unit_num2date.py @@ -249,9 +249,7 @@ def test_fractional_second_360_day(self): def test_pydatetime_wrong_calendar(self): unit = cf_units.Unit("days since 1970-01-01", calendar="360_day") - with pytest.raises( - ValueError, match="illegal calendar or reference date" - ): + with pytest.raises(ValueError, match="illegal calendar or reference date"): unit.num2date( 1, only_use_cftime_datetimes=False, diff --git a/cf_units/tests/integration/test_num2date.py b/cf_units/tests/integration/test_num2date.py index 4f067e7b..f831ff29 100644 --- a/cf_units/tests/integration/test_num2date.py +++ b/cf_units/tests/integration/test_num2date.py @@ -4,7 +4,6 @@ # See LICENSE in the root of the repository for full licensing details. """Test function :func:`cf_units.num2date`.""" - import pytest from cf_units import num2date @@ -12,9 +11,7 @@ class Test: def test_num2date_wrong_calendar(self): - with pytest.raises( - ValueError, match="illegal calendar or reference date" - ): + with pytest.raises(ValueError, match="illegal calendar or reference date"): num2date( 1, "days since 1970-01-01", diff --git a/cf_units/tests/integration/test_num2pydate.py b/cf_units/tests/integration/test_num2pydate.py index 7067c4c9..fbc51949 100644 --- a/cf_units/tests/integration/test_num2pydate.py +++ b/cf_units/tests/integration/test_num2pydate.py @@ -19,7 +19,5 @@ def test_num2pydate_simple(self): assert isinstance(result, datetime.datetime) def test_num2pydate_wrong_calendar(self): - with pytest.raises( - ValueError, match="illegal calendar or reference date" - ): + with pytest.raises(ValueError, match="illegal calendar or reference date"): num2pydate(1, "days since 1970-01-01", calendar="360_day") diff --git a/cf_units/tests/test_coding_standards.py b/cf_units/tests/test_coding_standards.py index 98cf40e7..08fd3bbe 100644 --- a/cf_units/tests/test_coding_standards.py +++ b/cf_units/tests/test_coding_standards.py @@ -28,9 +28,7 @@ exclusion = ["Makefile", "make.bat", "build"] DOCS_DIRS = glob(os.path.join(DOCS_DIR, "*")) DOCS_DIRS = [ - DOC_DIR - for DOC_DIR in DOCS_DIRS - if os.path.basename(DOC_DIR) not in exclusion + DOC_DIR for DOC_DIR in DOCS_DIRS if os.path.basename(DOC_DIR) not in exclusion ] @@ -104,9 +102,7 @@ def test_license_headers(self): last_change_by_fname = self.last_change_by_fname() except ValueError: # Caught the case where this is not a git repo. - return pytest.skip( - "cf_units installation did not look like a " "git repo." - ) + return pytest.skip("cf_units installation did not look like a " "git repo.") failed = False for fname, last_change in sorted(last_change_by_fname.items()): @@ -126,6 +122,4 @@ def test_license_headers(self): failed = True if failed: - raise AssertionError( - "There were license header failures. See stdout." - ) + raise AssertionError("There were license header failures. See stdout.") diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 6bc1ad82..d1e422b8 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -164,9 +164,7 @@ def test_format_multiple_options(self): def test_format_multiple_options_utf8(self): u = Unit("watt") assert ( - u.format( - [cf_units.UT_NAMES, cf_units.UT_DEFINITION, cf_units.UT_UTF8] - ) + u.format([cf_units.UT_NAMES, cf_units.UT_DEFINITION, cf_units.UT_UTF8]) == "meter²·kilogram·second⁻³" ) @@ -889,9 +887,7 @@ def test_multidim_masked(self): # Manufacture a Fortran-ordered nd array to be converted. orig = ( - np.ma.masked_array( - np.arange(4, dtype=np.float32), mask=[1, 0, 0, 1] - ) + np.ma.masked_array(np.arange(4, dtype=np.float32), mask=[1, 0, 0, 1]) .reshape([2, 2]) .T ) @@ -971,9 +967,7 @@ def test_num2date_wrong_calendar(self): "hours since 2010-11-02 12:00:00", calendar=cf_units.CALENDAR_360_DAY, ) - with pytest.raises( - ValueError, match="illegal calendar or reference date" - ): + with pytest.raises(ValueError, match="illegal calendar or reference date"): u.num2date( 1, only_use_cftime_datetimes=False, @@ -1003,9 +997,7 @@ def test_num2pydate_wrong_calendar(self): "hours since 2010-11-02 12:00:00", calendar=cf_units.CALENDAR_360_DAY, ) - with pytest.raises( - ValueError, match="illegal calendar or reference date" - ): + with pytest.raises(ValueError, match="illegal calendar or reference date"): u.num2pydate(1) diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index 973c8a31..607c60a3 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -67,19 +67,17 @@ def test_parse(self): assert unit is not None def test_parse_latin1(self): - angstrom = _ud.parse(self.system, b"\xe5ngstr\xF6m", _ud.UT_LATIN1) + angstrom = _ud.parse(self.system, b"\xe5ngstr\xf6m", _ud.UT_LATIN1) assert angstrom is not None def test_parse_ISO_8859_1(self): - angstrom = _ud.parse(self.system, b"\xe5ngstr\xF6m", _ud.UT_ISO_8859_1) + angstrom = _ud.parse(self.system, b"\xe5ngstr\xf6m", _ud.UT_ISO_8859_1) assert angstrom is not None def test_parse_UTF8(self): - angstrom = _ud.parse( - self.system, b"\xc3\xa5ngstr\xc3\xb6m", _ud.UT_UTF8 - ) + angstrom = _ud.parse(self.system, b"\xc3\xa5ngstr\xc3\xb6m", _ud.UT_UTF8) assert angstrom is not None @@ -222,9 +220,7 @@ def test_encode_date(self): assert self.date_encoding == res_date_encoding def test_encode_clock(self): - res_clock_encoding = _ud.encode_clock( - self.hours, self.minutes, self.seconds - ) + res_clock_encoding = _ud.encode_clock(self.hours, self.minutes, self.seconds) assert self.clock_encoding == res_clock_encoding @@ -259,9 +255,7 @@ def test_decode_time(self): self.minutes, ) assert ( - res_seconds - res_resolution - < self.seconds - < res_seconds + res_resolution + res_seconds - res_resolution < self.seconds < res_seconds + res_resolution ) diff --git a/cf_units/tests/unit/unit/test_Unit.py b/cf_units/tests/unit/unit/test_Unit.py index 2293cbae..5d80d75c 100644 --- a/cf_units/tests/unit/unit/test_Unit.py +++ b/cf_units/tests/unit/unit/test_Unit.py @@ -4,7 +4,6 @@ # See LICENSE in the root of the repository for full licensing details. """Unit tests for the `cf_units.Unit` class.""" - import numpy as np import pytest @@ -213,9 +212,7 @@ class Test_convert__result_ctype: def setup_method(self): self.initial_dtype = np.float32 - self.degs_array = np.array( - [356.7, 356.8, 356.9], dtype=self.initial_dtype - ) + self.degs_array = np.array([356.7, 356.8, 356.9], dtype=self.initial_dtype) self.deg = cf_units.Unit("degrees") self.rad = cf_units.Unit("radians") @@ -255,15 +252,11 @@ def setup_method(self): ) def test_no_type_conversion(self): - result = self.deg.convert( - self.degs_array, self.rad, ctype=cf_units.FLOAT32 - ) + result = self.deg.convert(self.degs_array, self.rad, ctype=cf_units.FLOAT32) np.testing.assert_array_almost_equal(self.rads_array, result) def test_type_conversion(self): - result = self.deg.convert( - self.degs_array, self.rad, ctype=cf_units.FLOAT64 - ) + result = self.deg.convert(self.degs_array, self.rad, ctype=cf_units.FLOAT64) np.testing.assert_array_almost_equal(self.rads_array, result) @@ -271,9 +264,7 @@ class Test_is_long_time_interval: @staticmethod def test_deprecated(): unit = Unit("seconds since epoch") - with pytest.warns( - DeprecationWarning, match="This method is no longer needed" - ): + with pytest.warns(DeprecationWarning, match="This method is no longer needed"): _ = unit.is_long_time_interval() def test_short_time_interval(self): diff --git a/cf_units/util.py b/cf_units/util.py index 2f5841bf..dd49af84 100644 --- a/cf_units/util.py +++ b/cf_units/util.py @@ -79,9 +79,7 @@ def __new__(cls, name, bases, namespace): ) exec(method_source, namespace) - return super(_MetaOrderedHashable, cls).__new__( - cls, name, bases, namespace - ) + return super(_MetaOrderedHashable, cls).__new__(cls, name, bases, namespace) class _OrderedHashable(Hashable, metaclass=_MetaOrderedHashable): diff --git a/setup.py b/setup.py index d508892c..f895cc70 100644 --- a/setup.py +++ b/setup.py @@ -133,9 +133,7 @@ def _set_builtin(name, value): library_dirs=library_dirs, libraries=["udunits2"], define_macros=DEFINE_MACROS, - runtime_library_dirs=( - None if sys.platform.startswith("win") else library_dirs - ), + runtime_library_dirs=(None if sys.platform.startswith("win") else library_dirs), ) if cythonize: