You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There's two rules (F509, PLE1300) that detect when a % formatted string include an invalid format character. However, these don't seem to flag format strings passed to logging functions (debug, info, etc.). These strings use % for formatting in the same way.
To confirm that this is an error, comment out the x = ... line and run the code. It prints:
--- Logging error ---
Traceback (most recent call last):
File "/Users/huon/.pyenv/versions/3.10.4/lib/python3.10/logging/__init__.py", line 1100, in emit
msg = self.format(record)
File "/Users/huon/.pyenv/versions/3.10.4/lib/python3.10/logging/__init__.py", line 943, in format
return fmt.format(record)
File "/Users/huon/.pyenv/versions/3.10.4/lib/python3.10/logging/__init__.py", line 678, in format
record.message = record.getMessage()
File "/Users/huon/.pyenv/versions/3.10.4/lib/python3.10/logging/__init__.py", line 368, in getMessage
msg = msg % self.args
ValueError: unsupported format character 'A' (0x41) at index 10
Call stack:
File "/private/tmp/test.py", line 6, in <module>
logging.error("ignored: %A", 1) # no error
Message: 'ignored: %A'
Arguments: (1,)
I think it's a little bit complicated than that. The formatting is decided by the Formatter objects which can use % but it can also use other formatting style which is determined by the style parameter and it can be set separately for each logger or can be set through the global config.
Or, maybe we can just check if the string uses %-style format characters and make an assumption that it uses the % style.
In addition, there's existing linting rules that explicitly suggest turning f-strings and .format calls into %, so "use % for logging" is an assumption with precedent:
There's two rules (F509, PLE1300) that detect when a
%
formatted string include an invalid format character. However, these don't seem to flag format strings passed to logging functions (debug
,info
, etc.). These strings use%
for formatting in the same way.(References: "The message attribute of the record is computed using msg % args" https://docs.python.org/3/library/logging.html#logging.Formatter.format , https://github.com/python/cpython/blob/9728ead36181fb3f0a4b2e8a7291a3e0a702b952/Lib/logging/__init__.py#L391-L401).
Reproducer: https://play.ruff.rs/36d5756e-44c7-48a1-8d8e-ae45a29ee480
Settings (note
"select": ["ALL"]
)To confirm that this is an error, comment out the
x = ...
line and run the code. It prints:Issues that are (somewhat) related:
flake8-logging
#7248F509
andPLE1300
#11403Thanks for ruff, very speedy!
The text was updated successfully, but these errors were encountered: