Skip to content

Commit 5ace689

Browse files
refactor: simplify conditionals and modernize datetime usage
Apply small structural cleanups in filesize, lists, number, and time modules (ternaries, Yoda comparison, zip strict=True). Use dt.UTC in tests per pyupgrade. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 42b4a1d commit 5ace689

6 files changed

Lines changed: 17 additions & 31 deletions

File tree

src/humanize/filesize.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,8 @@ def naturalsize(
8383
"""
8484
if gnu:
8585
suffix = suffixes["gnu"]
86-
elif binary:
87-
suffix = suffixes["binary"]
8886
else:
89-
suffix = suffixes["decimal"]
87+
suffix = suffixes["binary"] if binary else suffixes["decimal"]
9088

9189
base = 1024 if (gnu or binary) else 1000
9290
bytes_ = float(value)

src/humanize/lists.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ def natural_list(items: list[Any]) -> str:
3232
return ""
3333
if len(items) == 1:
3434
return str(items[0])
35-
elif len(items) == 2:
36-
return f"{str(items[0])} and {str(items[1])}"
37-
else:
38-
return ", ".join([str(item) for item in items[:-1]]) + f" and {str(items[-1])}"
35+
if len(items) == 2:
36+
return f"{items[0]!s} and {items[1]!s}"
37+
return ", ".join([str(item) for item in items[:-1]]) + f" and {items[-1]!s}"

src/humanize/number.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,8 @@ def _format_not_finite(value: float) -> str:
5656

5757
if math.isnan(value):
5858
return "NaN"
59-
if math.isinf(value) and value < 0:
60-
return "-Inf"
61-
if math.isinf(value) and value > 0:
62-
return "+Inf"
59+
if math.isinf(value):
60+
return "+Inf" if value > 0 else "-Inf"
6361
return ""
6462

6563

@@ -156,21 +154,15 @@ def intcomma(value: NumberOrString, ndigits: int | None = None) -> str:
156154
value = value.replace(thousands_sep, "").replace(decimal_sep, ".")
157155
if not math.isfinite(float(value)):
158156
return _format_not_finite(float(value))
159-
if "." in value:
160-
value = float(value)
161-
else:
162-
value = int(value)
157+
value = float(value) if "." in value else int(value)
163158
else:
164159
if not math.isfinite(float(value)):
165160
return _format_not_finite(float(value))
166161
float(value)
167162
except (TypeError, ValueError):
168163
return str(value)
169164

170-
if ndigits is not None:
171-
result = f"{value:,.{ndigits}f}"
172-
else:
173-
result = f"{value:,}"
165+
result = f"{value:,.{ndigits}f}" if ndigits is not None else f"{value:,}"
174166
if thousands_sep != "," or decimal_sep != ".":
175167
result = result.translate(str.maketrans(",.", thousands_sep + decimal_sep))
176168
return result
@@ -547,12 +539,12 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:
547539

548540
old_bucket = exponent // 3 * 3
549541
value /= 10**old_bucket
550-
digits = int(max(0, precision - exponent % 3 - 1))
542+
digits = max(0, precision - exponent % 3 - 1)
551543
if exponent < 30 and round(abs(value), digits) >= 1000:
552544
exponent += 3 - exponent % 3
553545
new_bucket = exponent // 3 * 3
554546
value /= 10 ** (new_bucket - old_bucket)
555-
digits = int(max(0, precision - exponent % 3 - 1))
547+
digits = max(0, precision - exponent % 3 - 1)
556548

557549
if exponent >= 3:
558550
ordinal_ = "kMGTPEZYRQ"[exponent // 3 - 1]
@@ -561,9 +553,6 @@ def metric(value: float, unit: str = "", precision: int = 3) -> str:
561553
else:
562554
ordinal_ = ""
563555
value_ = format(value, f".{digits}f")
564-
if not (unit or ordinal_) or unit in ("°", "′", "″"):
565-
space = ""
566-
else:
567-
space = " "
556+
space = "" if not (unit or ordinal_) or unit in ("°", "′", "″") else " "
568557

569558
return f"{value_}{space}{ordinal_}{unit}"

src/humanize/time.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ def naturaldelta(
195195

196196
return _ngettext("%d minute", "%d minutes", minutes) % minutes
197197

198-
if 3600 <= delta.seconds:
198+
if delta.seconds >= 3600:
199199
hours = round(delta.seconds / 3600)
200200
if hours == 1:
201201
return _("an hour")
@@ -643,7 +643,7 @@ def precisedelta(
643643
import math
644644

645645
texts: list[str] = []
646-
for unit, fmt in zip(reversed(Unit), fmts):
646+
for unit, fmt in zip(reversed(Unit), fmts, strict=True):
647647
singular_txt, plural_txt, fmt_value = fmt
648648
if fmt_value > 0 or (not texts and unit == min_unit):
649649
_fmt_value = 2 if 1 < fmt_value < 2 else int(fmt_value)

tests/test_i18n.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import humanize
1212

1313
with freeze_time("2020-02-02"):
14-
NOW = dt.datetime.now(tz=dt.timezone.utc)
14+
NOW = dt.datetime.now(tz=dt.UTC)
1515

1616

1717
@freeze_time("2020-02-02")

tests/test_time.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
with freeze_time(FROZEN_DATE):
2929
NOW = dt.datetime.now()
30-
NOW_UTC = dt.datetime.now(tz=dt.timezone.utc)
30+
NOW_UTC = dt.datetime.now(tz=dt.UTC)
3131
NOW_UTC_PLUS_01_00 = dt.datetime.now(tz=dt.timezone(offset=dt.timedelta(hours=1)))
3232
TODAY = dt.date.today()
3333
TOMORROW = TODAY + ONE_DAY_DELTA
@@ -66,7 +66,7 @@ def test_date_and_delta() -> None:
6666
td_tests = [td(seconds=x) for x in int_tests]
6767
results = [(now - td(seconds=x), td(seconds=x)) for x in int_tests]
6868
for t in (int_tests, date_tests, td_tests):
69-
for arg, result in zip(t, results):
69+
for arg, result in zip(t, results, strict=True):
7070
date, d = time._date_and_delta(arg)
7171
assert_equal_datetime(date, result[0])
7272
assert_equal_timedelta(d, result[1])
@@ -303,7 +303,7 @@ def test_naturaldate(test_input: dt.date, expected: str) -> None:
303303
@freeze_time("2023-10-15 23:00:00+00:00")
304304
def test_naturaldate_tz_aware() -> None:
305305
"""naturaldate should compare dates in the timezone of the given value."""
306-
utc = dt.timezone.utc
306+
utc = dt.UTC
307307
aedt = dt.timezone(dt.timedelta(hours=11))
308308
cest = dt.timezone(dt.timedelta(hours=2))
309309
edt = dt.timezone(dt.timedelta(hours=-4))

0 commit comments

Comments
 (0)