56 lines
1.6 KiB
Plaintext
56 lines
1.6 KiB
Plaintext
![]() |
This rule raises an issue when "f-strings" are deeply nested.
|
|||
|
|
|||
|
== Why is this an issue?
|
|||
|
|
|||
|
Through https://peps.python.org/pep-0701/[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:
|
|||
|
|
|||
|
[source,python]
|
|||
|
----
|
|||
|
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:
|
|||
|
|
|||
|
[source,python]
|
|||
|
----
|
|||
|
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
|
|||
|
|
|||
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|||
|
----
|
|||
|
hello = "Hello"
|
|||
|
name = "John"
|
|||
|
my_string = f"{f"{f"{hello}"},"} {name}!" # Noncompliant: deep nesting of "f-strings" is confusing
|
|||
|
----
|
|||
|
|
|||
|
==== Compliant solution
|
|||
|
|
|||
|
[source,python,diff-id=1,diff-type=compliant]
|
|||
|
----
|
|||
|
hello = "Hello"
|
|||
|
name = "John"
|
|||
|
greeting = f"{f"{hello}"},"
|
|||
|
my_string = f"{greeting} {name}!" # Compliant
|
|||
|
----
|
|||
|
|
|||
|
|
|||
|
== Resources
|
|||
|
=== Documentation
|
|||
|
|
|||
|
* PEP 701 - https://peps.python.org/pep-0701/[Syntactic formalization of "f-strings"]
|
|||
|
* Python Release Notes - https://docs.python.org/3/whatsnew/3.12.html#what-s-new-in-python-3-12[What’s New In Python 3.12]
|