Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed May 1, 2024
1 parent f3603c6 commit e84e679
Show file tree
Hide file tree
Showing 16 changed files with 58 additions and 160 deletions.
76 changes: 21 additions & 55 deletions cf_units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1796,24 +1769,19 @@ 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
# Utilise global convenience dictionary
# _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:
Expand All @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions cf_units/_udunits2_parser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
}


Expand Down
4 changes: 1 addition & 3 deletions cf_units/_udunits2_parser/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
1 change: 0 additions & 1 deletion cf_units/_udunits2_parser/parser/udunits2Lexer.py
Original file line number Diff line number Diff line change
@@ -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 *

Expand Down
41 changes: 10 additions & 31 deletions cf_units/_udunits2_parser/parser/udunits2Parser.py
Original file line number Diff line number Diff line change
@@ -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 *

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 4 additions & 6 deletions cf_units/tests/integration/parse/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
1 change: 0 additions & 1 deletion cf_units/tests/integration/test__Unit_date2num.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 1 addition & 3 deletions cf_units/tests/integration/test__Unit_num2date.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 1 addition & 4 deletions cf_units/tests/integration/test_num2date.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@
# 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


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",
Expand Down
Loading

0 comments on commit e84e679

Please sign in to comment.