New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[SIM121] Use ".get" instead of "if X in dict: dict[X]" #50
Labels
enhancement
New feature or request
Comments
|
Related:
|
False-Positive (solved):
|
False-positive:
|
MartinThoma
changed the title
[New Rule] Use ".get" instead of "if X in dict: dict[X]"
[SIM121] Use ".get" instead of "if X in dict: dict[X]"
Mar 28, 2021
I've also seen:
|
Kind of related, but might suit a separate rule: # bad
if key in some_dict:
some_dict[key].append(value)
else:
some_dict[key] = [value]
# good
from collections import defaultdict
some_dict = defaultdict(list)
some_dict[key].append(value) + sets, dicts as values |
I've used defaultdict in the past, but in the past 1-2 years I've rather used this pattern: # bad
if key in some_dict:
some_dict[key].append(value)
else:
some_dict[key] = [value]
# Good
if key not in some_dict:
some_dict[key] = []
some_dict[key].append(value) I think it's typically clearer than a default dictionary, especially if the dictionary is passed to other functions. |
See #52 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation
The
get(key, default_fallback=None)
method of a dictionary is often overlooked. It provides a clear interface that every Python developer should know.Example
The text was updated successfully, but these errors were encountered: