org.sonar.l10n.py.rules.python.S6799.html Maven / Gradle / Ivy
This rule raises an issue when "f-strings" are deeply nested.
Why is this an issue?
Through PEP 701, Python 3.12 lifts restrictions on how to construct "f-strings".
Prior to Python 3.12, it was not possible to reuse string quotes when nesting "f-strings". Therefore, the maximum level of nesting was:
f"""{f'''{f'{f"{1+1}"}'}'''}"""
It is now possible to arbitrarily nest "f-strings" by reusing string quotes. The following snippet is therefore valid:
f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}"
It is, however, not recommended to nest "f-strings" too deeply as this would make the code confusing and hard to maintain.
This rule will raise an issue when "f-string" literals are nested 3 times or more.
How to fix it
To fix this issue, refactor the code to avoid nesting "f-string" literals too deeply. This may be done by introducing new variables to store
intermediate results.
Code examples
Noncompliant code example
hello = "Hello"
name = "John"
my_string = f"{f"{f"{hello}"},"} {name}!" # Noncompliant: deep nesting of "f-strings" is confusing
Compliant solution
hello = "Hello"
name = "John"
greeting = f"{f"{hello}"},"
my_string = f"{greeting} {name}!" # Compliant
Resources
Documentation
- PEP 701 - Syntactic formalization of "f-strings"
- Python Release Notes - What’s New In Python 3.12