All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6799.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy