Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff: smaller steps #364

Merged
merged 34 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
4e3f4f1
config changes from #353
rcomer May 3, 2023
6eea3df
keep existing line length and import sort order
rcomer May 3, 2023
a440dfb
remove flake8 config
rcomer May 3, 2023
e943de3
Drop black; update ruff version and add formatter
rcomer Nov 13, 2023
8ca2c81
ruff autofixes
rcomer Nov 13, 2023
e4c389d
ruff formatter fix
rcomer Nov 13, 2023
5044a17
ruff 'unsafe' autofixes
rcomer Nov 14, 2023
253f8f5
Ruth fixes for unsafe fixes
rcomer Nov 14, 2023
2a5ceb3
re-run ruff formatter
rcomer Nov 14, 2023
6ab3127
Manually address E501 and B018
rcomer Nov 14, 2023
48bdcdc
point to astral-sh organisation; tidy some broken strings
rcomer Nov 15, 2023
23c47fb
review actions
rcomer Feb 26, 2024
47592b4
Merge branch 'main' into ruff
stephenworsley Sep 24, 2024
b318ace
update ruff-pre-commit version
stephenworsley Sep 24, 2024
cfe6fdc
fix pyproject.toml
stephenworsley Sep 24, 2024
2613ef9
fix pyproject.toml
stephenworsley Sep 24, 2024
94f6cb5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 24, 2024
e5b3f71
ruff fixes
stephenworsley Sep 24, 2024
da23120
Merge remote-tracking branch 'rcomer/ruff' into ruff
stephenworsley Sep 24, 2024
e432482
fix parantheses
stephenworsley Sep 24, 2024
5dfccb2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 24, 2024
f73d466
more lint fixes
stephenworsley Sep 24, 2024
153cf9b
Merge remote-tracking branch 'rcomer/ruff' into ruff
stephenworsley Sep 24, 2024
bb2d5dc
linting + pre-commit fixes
stephenworsley Sep 25, 2024
889c4bd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 25, 2024
b15e353
linting + pre-commit fixes
stephenworsley Sep 25, 2024
f3179e6
Merge remote-tracking branch 'rcomer/ruff' into ruff
stephenworsley Sep 25, 2024
59e3f10
fix test
stephenworsley Sep 25, 2024
3fccd63
revert ruff fix
stephenworsley Sep 25, 2024
a1cd41f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 25, 2024
e0b930c
ignore generated code
stephenworsley Sep 25, 2024
730df15
Merge remote-tracking branch 'rcomer/ruff' into ruff
stephenworsley Sep 25, 2024
f82ea4b
remove redundant ignore
stephenworsley Sep 25, 2024
bbd902c
Merge branch 'main' into ruff
stephenworsley Sep 25, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 16 additions & 21 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,6 @@ repos:
# Don't commit to main branch.
- id: no-commit-to-branch

- repo: https://github.com/psf/black
rev: 24.8.0
hooks:
- id: black
types: [file, python]
args: [--config=./pyproject.toml]

- repo: https://github.com/PyCQA/flake8
rev: 7.1.1
hooks:
- id: flake8
types: [file, python]
args: [--config=./setup.cfg]

- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
types: [file, python]
args: [--filter-files]

- repo: https://github.com/aio-libs/sort-all
rev: v1.2.0
hooks:
Expand All @@ -52,3 +31,19 @@ repos:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"] # TODO: Only neededed if extra dependencies are required
#args: ["--show=errskip"] # show everything for the moment

- repo: https://github.com/adamchainz/blacken-docs
rev: 1.16.0
hooks:
- id: blacken-docs
types: [file, rst]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.4.10"
hooks:
# Run the linter
- id: ruff
types: [file, python]
args: [--fix, --show-fixes]
# Run the formatter.
- id: ruff-format
77 changes: 37 additions & 40 deletions cf_units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,10 @@ def suppress_errors():
try:
_ud_system = _ud.read_xml(config.get_xml_path())
except _ud.UdunitsError as e:
error_msg = ': "%s"' % e.error_msg() if e.errnum else ""
error_msg = f': "{e.error_msg():s}"' if e.errnum else ""
raise OSError(
"[%s] Failed to open UDUNITS-2 XML unit database%s"
% (e.status_msg(), error_msg)
f"[{e.status_msg()}] "
f"Failed to open UDUNITS-2 XML unit database{error_msg}"
pelson marked this conversation as resolved.
Show resolved Hide resolved
)


Expand Down Expand Up @@ -498,7 +498,7 @@ def as_unit(unit):
result = unit
else:
result = None
use_cache = isinstance(unit, (str,)) or unit is None
use_cache = isinstance(unit, str) or unit is None
if use_cache:
result = _CACHE.get(unit)
if result is None:
Expand Down Expand Up @@ -566,11 +566,9 @@ def _ud_value_error(ud_err, message):

ud_msg = ud_err.error_msg()
if ud_msg:
message = "{}: {}".format(message, ud_msg)
message = f"{message}: {ud_msg}"

message = "[{status}] {message}".format(
status=ud_err.status_msg(), message=message
)
message = f"[{ud_err.status_msg()}] {message}"

return ValueError(message)

Expand All @@ -594,7 +592,7 @@ class Unit(_OrderedHashable):
def _init_from_tuple(self, values):
# Implements the required interface for an _OrderedHashable.
# This will also ensure a Unit._init(*Unit.names) method exists.
for name, value in zip(self._names, values):
for name, value in zip(self._names, values, strict=False):
object.__setattr__(self, name, value)

# Provide hash semantics
Expand All @@ -614,12 +612,12 @@ def __lt__(self, other):

def __setattr__(self, name, value):
raise AttributeError(
"Instances of %s are immutable" % type(self).__name__
f"Instances of {type(self).__name__:s} are immutable"
)

def __delattr__(self, name):
raise AttributeError(
"Instances of %s are immutable" % type(self).__name__
f"Instances of {type(self).__name__:s} are immutable"
)

# Declare the attribute names relevant to the ordered and hashable
Expand Down Expand Up @@ -727,13 +725,13 @@ def __init__(self, unit, calendar=None):
ut_unit = _ud.parse(_ud_system, unit.encode("utf8"), encoding)
except _ud.UdunitsError as exception:
value_error = _ud_value_error(
exception, 'Failed to parse unit "{}"'.format(str_unit)
exception, f'Failed to parse unit "{str_unit}"'
)
raise value_error from None
if _OP_SINCE in unit.lower():
if calendar is None:
calendar_ = CALENDAR_STANDARD
elif isinstance(calendar, (str,)):
elif isinstance(calendar, str):
calendar_ = calendar.lower()
if calendar_ in CALENDAR_ALIASES:
calendar_ = CALENDAR_ALIASES[calendar_]
Expand Down Expand Up @@ -932,7 +930,7 @@ def title(self, value):
dt = self.num2date(value)
result = dt.strftime("%Y-%m-%d %H:%M:%S")
else:
result = "%s %s" % (str(value), self)
result = f"{value} {self}"
return result

@property
Expand Down Expand Up @@ -1220,15 +1218,15 @@ def offset_by_time(self, origin):

"""

if not isinstance(origin, (float, (int,))):
if not isinstance(origin, float | int):
raise TypeError(
"a numeric type for the origin argument is" " required"
"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:
value_error = _ud_value_error(
exception, "Failed to offset {!r}".format(self)
exception, f"Failed to offset {self!r}"
)
raise value_error from None
calendar = None
Expand Down Expand Up @@ -1300,7 +1298,7 @@ def root(self, root):
except _ud.UdunitsError as exception:
value_error = _ud_value_error(
exception,
"Failed to take the root of {!r}".format(self),
f"Failed to take the root of {self!r}",
)
raise value_error from None
calendar = None
Expand Down Expand Up @@ -1338,13 +1336,12 @@ def log(self, base):
ut_unit = _ud.log(base, self.ut_unit)
except TypeError:
raise TypeError(
"A numeric type for the base argument is " " required"
"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),
f"Failed to calculate logorithmic base of {self!r}",
)
raise value_err from None
calendar = None
Expand Down Expand Up @@ -1386,10 +1383,11 @@ def __repr__(self):

"""
if self.calendar is None:
result = "{}('{}')".format(self.__class__.__name__, self)
result = f"{self.__class__.__name__}('{self}')"
else:
result = "{}('{}', calendar='{}')".format(
self.__class__.__name__, self, self.calendar
result = (
f"{self.__class__.__name__}"
f"('{self}', calendar='{self.calendar}')"
)
return result

Expand Down Expand Up @@ -1430,7 +1428,7 @@ def _op_common(self, other, op_func):
other = as_unit(other)

if self.is_no_unit() or other.is_no_unit():
raise ValueError("Cannot %s a 'no-unit'." % op_label)
raise ValueError(f"Cannot {op_label:s} a 'no-unit'.")

if self.is_unknown() or other.is_unknown():
result = Unit(_UNKNOWN_UNIT_STRING)
Expand All @@ -1440,7 +1438,7 @@ def _op_common(self, other, op_func):
except _ud.UdunitsError as exception:
value_err = _ud_value_error(
exception,
"Failed to {} {!r} by {!r}".format(op_label, self, other),
f"Failed to {op_label} {self!r} by {other!r}",
)
raise value_err from None
calendar = None
Expand Down Expand Up @@ -1583,10 +1581,10 @@ def __pow__(self, power):
root = int(round(1 / power))
result = self.root(root)
else:
# Failing that, check for powers which are (very nearly) simple
# integer values.
# Failing that, check for powers which are (very nearly)
# simple integer values.
if not math.isclose(power, round(power)):
msg = "Cannot raise a unit by a decimal (got %s)." % power
msg = f"Cannot raise a unit by a decimal (got {power:s})."
raise ValueError(msg)
power = int(round(power))

Expand All @@ -1595,7 +1593,7 @@ def __pow__(self, power):
except _ud.UdunitsError as exception:
value_err = _ud_value_error(
exception,
"Failed to raise the power of {!r}".format(self),
f"Failed to raise the power of {self!r}",
)
raise value_err from None
result = Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit)
Expand Down Expand Up @@ -1662,10 +1660,10 @@ def __ne__(self, other):

def change_calendar(self, calendar):
"""
Returns a new unit with the requested calendar, modifying the reference
date if necessary. Only works with calendars that represent the real
world (standard, proleptic_gregorian, julian) and with short time
intervals (days or less).
Returns a new unit with the requested calendar, modifying the
reference date if necessary. Only works with calendars that
represent the real world (standard, proleptic_gregorian, julian)
and with short time intervals (days or less).

For example:

Expand All @@ -1674,7 +1672,7 @@ def change_calendar(self, calendar):
>>> u.change_calendar('standard')
Unit('days since 1499-12-23T00:00:00', calendar='standard')

"""
""" # NOQA E501
pelson marked this conversation as resolved.
Show resolved Hide resolved
if not self.is_time_reference():
raise ValueError("unit is not a time reference")

Expand Down Expand Up @@ -1772,7 +1770,7 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False):
except _ud.UdunitsError as exception:
value_err = _ud_value_error(
exception,
"Failed to convert {!r} to {!r}".format(self, other),
f"Failed to convert {self!r} to {other!r}",
)
raise value_err from None
if isinstance(result, np.ndarray):
Expand All @@ -1796,9 +1794,8 @@ 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,
np.float64,
"Expect a numpy array of "
f"'{np.float32}' or '{np.float64}'"
)
ctype = result.dtype.type
# Utilise global convenience dictionary
Expand Down Expand Up @@ -1830,7 +1827,7 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False):
return result
else:
raise ValueError(
"Unable to convert from '%r' to '%r'." % (self, other)
f"Unable to convert from '{self!r}' to '{other!r}'."
)

@property
Expand Down
4 changes: 2 additions & 2 deletions cf_units/_udunits2_parser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def __init__(self, unit_string):

def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
# https://stackoverflow.com/a/36367357/741316
context = ("inline", line, column + 2, "'{}'".format(self.unit_string))
context = ("inline", line, column + 2, f"'{self.unit_string}'")
syntax_error = SyntaxError(msg, context)
raise syntax_error from None

Expand All @@ -192,7 +192,7 @@ def _debug_tokens(unit_string):
continue
token_type_idx = token.type
rule = TOKEN_ID_NAMES[token_type_idx]
print("%s: %s" % (token.text, rule))
print(f"{token.text}: {rule}")


def normalize(unit_string):
Expand Down
2 changes: 1 addition & 1 deletion cf_units/_udunits2_parser/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def expand_lexer(source, target):
MODE_P = re.compile(r"mode ([A-Z_]+)\;")
TOKEN_P = re.compile(r"([A-Z_]+) ?\:.*")

with open(source, "r") as fh:
with open(source) as fh:
content = fh.read()

template = jinja2.Environment(loader=jinja2.BaseLoader).from_string(
Expand Down
6 changes: 3 additions & 3 deletions cf_units/_udunits2_parser/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def __getattr__(self, name):
def _repr_ctx(self):
# Return a dictionary that is useful for passing to string.format.
kwargs = ", ".join(
"{}={!r}".format(key, value) for key, value in self._attrs.items()
f"{key}={value!r}" for key, value in self._attrs.items()
)
return dict(cls_name=self.__class__.__name__, kwargs=kwargs)
return {"cls_name": self.__class__.__name__, "kwargs": kwargs}

def __repr__(self):
return "{cls_name}({kwargs})".format(**self._repr_ctx())
Expand All @@ -49,7 +49,7 @@ def children(self):
return []

def __str__(self):
return "{}".format(self.content)
return f"{self.content}"


class Operand(Terminal):
Expand Down
1 change: 1 addition & 0 deletions cf_units/_udunits2_parser/parser/udunits2Lexer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/parser/udunits2Lexer.g4 by ANTLR 4.11.1
stephenworsley marked this conversation as resolved.
Show resolved Hide resolved
# encoding: utf-8
import sys
from io import StringIO

Expand Down
2 changes: 1 addition & 1 deletion cf_units/_udunits2_parser/parser/udunits2Parser.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/udunits2Parser.g4 by ANTLR 4.11.1
# Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/parser/udunits2Lexer.g4 by ANTLR 4.11.1
# encoding: utf-8
import sys
from io import StringIO
Expand Down
8 changes: 4 additions & 4 deletions cf_units/tests/integration/parse/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def test_invalid_units(_, unit_str):
# Double check that udunits2 can't parse this.
assert (
cf_valid is False
), "Unit {!r} is unexpectedly valid in UDUNITS2".format(unit_str)
), f"Unit {unit_str!r} is unexpectedly valid in UDUNITS2"

try:
normalize(unit_str)
Expand All @@ -178,7 +178,7 @@ def test_invalid_units(_, unit_str):
can_parse = False

# Now confirm that we couldn't parse this either.
msg = "Parser unexpectedly able to deal with {}".format(unit_str)
msg = f"Parser unexpectedly able to deal with {unit_str}"
assert can_parse is False, msg


Expand Down Expand Up @@ -242,7 +242,7 @@ def test_known_issues(_, unit_str, expected):
# These are the cases that don't work yet but which do work with udunits.

# Make sure udunits can read it.
cf_units.Unit(unit_str).symbol
_ = cf_units.Unit(unit_str).symbol

if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(SyntaxError):
Expand Down Expand Up @@ -293,7 +293,7 @@ def test_invalid_syntax_units(_, unit_str):
# allowed with our grammar.

with pytest.raises(ValueError):
cf_units.Unit(unit_str).symbol
_ = cf_units.Unit(unit_str).symbol

with pytest.raises(SyntaxError):
normalize(unit_str)
Loading
Loading