rspec/rules/S5685/python/rule.adoc

62 lines
2.2 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 the walrus operator is used in a way which makes the code confusing, as described in https://www.python.org/dev/peps/pep-0572/#exceptional-cases[PEP 572].
== Why is this an issue?
The https://www.python.org/dev/peps/pep-0572[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
[source,python,diff-id=1,diff-type=noncompliant]
----
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
[source,python,diff-id=1,diff-type=compliant]
----
v0 = v1 = f(p)
x = 10
f'{x}'
----
== Resources
=== Documentation
* Python Documentation - https://www.python.org/dev/peps/pep-0572[PEP 572 Assignment Expressions]
* Python Documentation - https://www.python.org/dev/peps/pep-0572/#exceptional-cases[PEP 572 - Assignment Expressions - Exceptional cases]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use an assignment statement ("=") instead; ":=" operator is confusing in this context
* Move this assignment out of the f-string; ":=" operator is confusing in this context
=== Highlighting
The := operator
endif::env-github,rspecator-view[]