rspec/rules/S5428/python/rule.adoc

48 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
A common anti-pattern is to check that a key does not exist in a dictionary before adding it with a corresponding value. This pattern works but is less readable than the equivalent call to the built-in dictionary method "setdefault()".
Note that if a default value is set for every key of the dictionary it is possible to use python's ``++defaultdict++`` instead.
This rule raises an issue when a key presence is checked before being set. It only raises an issue when the value is a hard-coded string, number, list, dictionary or tuple. Computed values will not raise an issue as they can have side-effects.
=== 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
----
if "key" not in my_dictionary:
my_dictionary["key"] = ["a", "b", "c"] # Noncompliant
if "key" not in my_dictionary:
my_dictionary["key"] = generate_value() # Compliant. No issue is raised as generate_value() might have some side-effect.
----
=== 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
----
my_dictionary.setdefault("key", ["a", "b", "c"])
# OR, if ["a", "b", "c"] is the default value for every key
from collections import defaultdict
my_dictionary = defaultdict(lambda: ["a", "b", "c"])
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace this key check and dictionary update with a call to "setdefault"
endif::env-github,rspecator-view[]