rspec/rules/S5685/python/rule.adoc

62 lines
2.2 KiB
Plaintext
Raw Normal View History

2023-08-04 16:44:20 +02:00
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?
2021-04-28 16:49:39 +02:00
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.
2023-08-04 16:44:20 +02:00
Reasons why it is better to avoid using the walrus operator in Python:
2021-04-28 16:49:39 +02:00
2023-08-04 16:44:20 +02:00
* *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.
2021-04-28 16:49:39 +02:00
2023-08-04 16:44:20 +02:00
=== Code examples
2023-08-04 16:44:20 +02:00
==== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-08-04 16:44:20 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
2023-08-04 16:44:20 +02:00
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
2021-04-28 16:49:39 +02:00
----
2023-08-04 16:44:20 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2023-08-04 16:44:20 +02:00
[source,python,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
v0 = v1 = f(p)
x = 10
2023-08-04 16:44:20 +02:00
f'{x}'
2021-04-28 16:49:39 +02:00
----
== Resources
2021-04-28 16:49:39 +02:00
2023-08-04 16:44:20 +02:00
=== 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[]