org.sonar.l10n.py.rules.python.S5685.html Maven / Gradle / Ivy
This rule raises an issue when the walrus operator is used in a way which makes the code confusing, as described in PEP 572.
Why is this an issue?
The walrus operator :=
(also known as "assignment expression") should be used
with caution as it can easily make code more difficult to understand and thus maintain. In such case it is advised to refactor the code and use an
assignment statement (i.e. =
) instead.
Reasons why it is better to avoid using the walrus operator in Python:
- Readability: The walrus operator can lead to more complex and nested expressions, which might reduce the readability of the
code, especially for developers who are not familiar with this feature.
- Compatibility: If you are working on projects that need to be compatible with older versions of Python (before 3.8), you
should avoid using the walrus operator, as it won’t be available in those versions.
How to fix it
Avoid using the walrus operator for the cases when it is not mandatory.
Code examples
Noncompliant code example
v0 = (v1 := f(p)) # Noncompliant: Use an assignment statement ("=") instead; ":=" operator is confusing in this context
f'{(x:=10)}' # Noncompliant: Move this assignment out of the f-string; ":=" operator is confusing in this context
Compliant solution
v0 = v1 = f(p)
x = 10
f'{x}'
Resources
Documentation
- Python Documentation - PEP 572 – Assignment Expressions
- Python Documentation - PEP 572 - Assignment Expressions - Exceptional
cases
© 2015 - 2024 Weber Informatics LLC | Privacy Policy