rspec/rules/S6799/python/rule.adoc
github-actions[bot] a128217967
Create rule S6799: f-strings should not be nested too deeply (#3211)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6799/python)
(updated a few minutes after each push).

## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)

---------

Co-authored-by: guillaume-dequenne-sonarsource <guillaume-dequenne-sonarsource@users.noreply.github.com>
Co-authored-by: David Kunzmann <david.kunzmann@sonarsource.com>
2023-11-01 11:32:07 +01:00

56 lines
1.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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[Whats New In Python 3.12]