MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

[New Rule] Default values for dictionaries #80

Open MartinThoma opened 2 years ago

MartinThoma commented 2 years ago

Explanation

It's a pretty typical situation that you have a dictionary and you need to do something with a value in there. If the key is not in there, you fill it (with another dict / a list / something else).

This rule simplifies the code as it removes code duplication.

Example

# Bad
if key in my_dict:
    my_dict = my_dict[key]
else:
    my_dict[key] = {}
    my_dict = my_dict[key]

# Good
if key not in my_dict:
    my_dict[key] = {}
my_dict = my_dict[key]
TomFryers commented 2 years ago

Or, even better, my_dict = my_dict.setdefault(key, {}).