54 lines
1.5 KiB
Plaintext
54 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
A common anti-pattern is to check that a key exists in a dictionary before retrieving its corresponding value and providing a default value otherwise. This pattern works but is less readable than the equivalent call to the built-in dictionary method "get()" with a default value.
|
|
|
|
|
|
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 retrieving its value or providing a default value. It only raises an issue when the default 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
|
|
|
|
[source,python]
|
|
----
|
|
result = "default"
|
|
if "missing" in mydict:
|
|
result = mydict["missing"] # Noncompliant
|
|
|
|
if "missing" in mydict:
|
|
result = mydict["missing"] # Noncompliant
|
|
else:
|
|
result = "default"
|
|
|
|
if "missing" in mydict:
|
|
result = mydict["missing"] # Compliant. No issue is raised as generate_value() might have some side-effect.
|
|
else:
|
|
result = generate_value()
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,python]
|
|
----
|
|
result = mydict.get("missing", "default")
|
|
|
|
# OR, if "default" is the default value for every key
|
|
|
|
from collections import defaultdict
|
|
mydict = defaultdict(lambda: "default")
|
|
result = mydict["missing"]
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|