2023-08-04 12:57:58 +02:00

62 lines
1.9 KiB
Plaintext

This rule raises an issue when trying to access a dictionary key that does not exist.
== Why is this an issue?
Trying to access a dictionary key that does not exist will raise a `KeyError` exception.
When trying to access or remove a key that may not be there, several solutions are possible:
* Use the `get()` method instead of a subscription. It will return `None` for a missing key instead of raising a `KeyError`.
* Use the `setdefault()` method to provide keys that may be missing with a default value.
* Check that the key is present in the dictionary with the `if key in dict:` construct.
* Use a `try/except` block and handle the potential `KeyError` exception.
* Use a `defaultdict` instead of a regular `dict` object, and provide a `default_factory` attribute.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
def foo():
my_dict = {'k1': 42}
...
value = my_dict['k2'] # Noncompliant: the key "k2" does not exist.
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def foo():
my_dict = {'k1': 42}
...
if 'k2' in my_dict:
value = my_dict['k2']
----
== Resources
=== Documentation
* Python Documentation - https://docs.python.org/3/library/stdtypes.html?highlight=setdefault#dict.setdefault[dict - setdefault]
* Python Documentation - https://docs.python.org/3/library/collections.html#collections.defaultdict[defaultdict]
* Python Documentation - https://docs.python.org/3/library/collections.html?highlight=default_factory#collections.defaultdict.default_factory[defaultdict - default_factory]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Fix this access on a dictionary key that may be missing.
Fix this "pop" operation on a dictionary key that may be missing.
Fix this "del" operation on a dictionary key that may be missing.
'''
endif::env-github,rspecator-view[]