astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
30.71k stars 1.02k forks source link

UP031: fix for `"%.2X" % 1` generates broken code #12421

Closed radoering closed 1 month ago

radoering commented 1 month ago

I know fixing UP031 is unsafe, but in this case we can do better:

"%.2X" % 1 is converted to "{:.2X}".format(1) but should probably be converted to "{:02X}".format(1)

>>> "%.2X" % 1
'01'
>>> "%02X" % 1
'01'
>>> "{:02X}".format(1)
'01'
>>> "{:.2X}".format(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Precision not allowed in integer format specifier

Command: ruff check --select UP031 --fix --unsafe-fixes test.py Ruff Version: 0.5.3

charliermarsh commented 1 month ago

Agreed.

charliermarsh commented 1 month ago

So basically: use :0 rather than . for integer-only presentation types.