2020-06-22 13:16:10 +02:00

35 lines
2.0 KiB
Plaintext

:source-highlighter: prettify
:source-language: python
:source-indent: 0
Formatting strings, either with the `%` operator or `str.format` method, requires a valid string and arguments matching this string's replacement fields.
This also applies to loggers from the `logging` module. Internally they use `%-formatting`. The only difference is that they will log an error instead of raising an exception when provided arguments are invalid.
Formatted string literals, also called "f-strings", are generally simpler to use, and any syntax mistake will fail at compile time. However it is easy to forget curly braces and it won't raise any error.
This rule raises an issue when:
* A string formatted with `%` will not return the expected string because some arguments are not used.
* A string formatted with `str.format` will not return the expected string because some arguments are not used.
* An "f-string" doesn't contain any replacement field, which probably means that some curly braces are missing.
* Loggers will log an error because their message is not formatted properly.
// TODO add a MACRO to replace reference to rule S2275
Rule S2275 covers cases where formatting a string will raise an exception.
== Noncompliant Code Example
----
include::noncompliant.py[]
----
== Compliant Solution
----
include::noncompliant.py[]
----
== See
* https://docs.python.org/3/library/string.html#format-string-syntax[Python documentation - Format String Syntax]
* https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting[Python documentation - printf-style String Formatting]
* https://docs.python.org/3/howto/logging.html#loggers[Python documentation - Loggers]
* https://docs.python.org/3/howto/logging-cookbook.html#using-particular-formatting-styles-throughout-your-application[Python documentation - Using particular formatting styles throughout your application]
* https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals[Python documentation - Formatted string literals]