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 12 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
31 changes: 10 additions & 21 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,18 @@ repos:
# Don't commit to main branch.
- id: no-commit-to-branch

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

- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
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:
- id: sort-all
types: [file, python]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.1.5"
stephenworsley marked this conversation as resolved.
Show resolved Hide resolved
hooks:
# Run the linter
- id: ruff
types: [file, python]
args: [--fix]
# Run the formatter.
- id: ruff-format
42 changes: 19 additions & 23 deletions cf_units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ def suppress_errors():
except _ud.UdunitsError as e:
error_msg = ': "%s"' % e.error_msg() 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 @@ -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 Down Expand Up @@ -727,7 +725,7 @@ 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():
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 @@ -1222,13 +1220,13 @@ def offset_by_time(self, origin):

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,7 +1383,7 @@ 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
Expand Down Expand Up @@ -1440,7 +1437,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 @@ -1595,7 +1592,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 @@ -1674,7 +1671,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 +1769,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 +1793,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 +1826,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
4 changes: 2 additions & 2 deletions cf_units/_udunits2_parser/parser/udunits2Lexer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/parser/udunits2Lexer.g4 by ANTLR 4.11.1
# Generated from cf_units/_udunits2_parser/parser/udunits2Lexer.g4 by
# ANTLR 4.11.1
stephenworsley marked this conversation as resolved.
Show resolved Hide resolved
import sys
from io import StringIO

from antlr4 import *

Expand Down
8 changes: 3 additions & 5 deletions cf_units/_udunits2_parser/parser/udunits2Parser.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# Generated from /home/ruth/git_stuff/cf-units/cf_units/_udunits2_parser/udunits2Parser.g4 by ANTLR 4.11.1
# encoding: utf-8
# Generated from cf_units/_udunits2_parser/udunits2Parser.g4 by ANTLR 4.11.1
import sys
from io import StringIO

from antlr4 import *

Expand Down Expand Up @@ -2225,8 +2223,8 @@ def timezone_offset(self):
return localctx

def sempred(self, localctx: RuleContext, ruleIndex: int, predIndex: int):
if self._predicates == None:
self._predicates = dict()
if self._predicates is None:
self._predicates = {}
self._predicates[2] = self.product_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
Expand Down
2 changes: 1 addition & 1 deletion cf_units/_udunits2_parser/parser/udunits2ParserVisitor.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 cf_units/_udunits2_parser/udunits2Parser.g4 by ANTLR 4.11.1
from antlr4 import *

if __name__ is not None and "." in __name__:
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)
18 changes: 12 additions & 6 deletions cf_units/tests/integration/test__Unit_num2date.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ def test_simple_360_day(self):
self.udays,
self.udays,
]
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, nums[0], 0),
(0, nums[1], 0),
Expand Down Expand Up @@ -218,7 +219,8 @@ def test_fractional_360_day(self):
self.udays,
self.udays,
]
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, nums[0] * 60, 0),
(0, nums[1] * 60, 0),
Expand All @@ -234,7 +236,8 @@ def test_fractional_second_360_day(self):
self.setup_units("360_day")
nums = [0.25, 0.5, 0.75, 1.5, 2.5, 3.5, 4.5]
units = [self.useconds] * 7
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, 0, 250000),
(0, 0, 500000),
Expand Down Expand Up @@ -273,7 +276,8 @@ def test_simple_365_day(self):
self.udays,
self.udays,
]
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, nums[0], 0),
(0, nums[1], 0),
Expand Down Expand Up @@ -305,7 +309,8 @@ def test_fractional_365_day(self):
self.udays,
self.udays,
]
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, nums[0] * 60, 0),
(0, nums[1] * 60, 0),
Expand All @@ -321,7 +326,8 @@ def test_fractional_second_365_day(self):
self.setup_units("365_day")
nums = [0.25, 0.5, 0.75, 1.5, 2.5, 3.5, 4.5]
units = [self.useconds] * 7
# Expected results in (days, seconds, microseconds) delta from unit epoch.
# Expected results in (days, seconds, microseconds) delta from unit
# epoch.
expected = [
(0, 0, 250000),
(0, 0, 500000),
Expand Down
4 changes: 2 additions & 2 deletions cf_units/tests/test_coding_standards.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def last_change_by_fname():
"""
pelson marked this conversation as resolved.
Show resolved Hide resolved
# Check the ".git" folder exists at the repo dir.
if not os.path.isdir(os.path.join(REPO_DIR, ".git")):
raise ValueError("{} is not a git repository.".format(REPO_DIR))
raise ValueError(f"{REPO_DIR} is not a git repository.")

# Call "git whatchanged" to get the details of all the files and when
# they were last changed.
Expand Down Expand Up @@ -109,7 +109,7 @@ def test_license_headers(self):
)

failed = False
for fname, last_change in sorted(last_change_by_fname.items()):
for fname in sorted(last_change_by_fname):
full_fname = os.path.join(REPO_DIR, fname)
if (
full_fname.endswith(".py")
Expand Down
2 changes: 1 addition & 1 deletion cf_units/tests/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,7 +833,7 @@ def test_time_unit(self):
class Test__immutable:
def _set_attr(self, unit, name):
setattr(unit, name, -999)
raise ValueError("'Unit' attribute {!r} is mutable!".format(name))
raise ValueError(f"'Unit' attribute {name!r} is mutable!")

def test_immutable(self):
u = Unit("m")
Expand Down
Loading
Loading