rspec/rules/S5685/python/rule.adoc

70 lines
1.8 KiB
Plaintext
Raw Normal View History

== 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.
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].
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
# using an assignment expression (:=) as an assignment statement (=) is more explicit
(v := f(p)) # Noncompliant
v0 = (v1 := f(p)) # Noncompliant
# using an assignment expression in a function call when keyword arguments are also used.
func(a=(b := f(p))) # Noncompliant
func(a := f(p), b=2) # Noncompliant
def func(param=(p := 21)): # Noncompliant
pass
# using an assignment expression in an annotation
def func(param: (p := 21) = 3): # Noncompliant
pass
# using assignment expression in an f-string. Character ":" is also used as a formatting marker in f-strings.
f'{(x:=10)}' # Noncompliant
f'{x:=10}' # No issue raised but still not recommended. This is not an assignment expression. '=10' is passed to the f-string formatter.
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
v = f(p)
v0 = v1 = f(p)
value = f(p)
func(a=value)
func(value, b=2)
def func(param=21):
p = 21
p = 21
def func(param: p = 3):
pass
x = 10
f'{x}'
----
== Resources
2021-04-28 16:49:39 +02:00
* https://www.python.org/dev/peps/pep-0572/#exceptional-cases[PEP 572 - Assignment Expressions]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]