wemake-services / wemake-python-styleguide

The strictest and most opinionated python linter ever!
https://wemake-python-styleguide.rtfd.io
MIT License
2.53k stars 378 forks source link

Enforce using `.setdefault()` #1085

Open sobolevn opened 4 years ago

sobolevn commented 4 years ago

Rule request

Thesis

One can write this code:


if "list" not in dictionary:
    dictionary["list"] = []

dictionary["list"].append("list_item")

But, it is an anti-pattern. Instead one should write:

dictionary = {}

dictionary.setdefault("list", []).append("list_item")

Related: https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_setdefault_to_initialize_a_dictionary.html

This is a refactoring rule.

adambenali commented 4 years ago

Should this be closed for the same reasons as #1084 ?

sobolevn commented 4 years ago

Yes, thank you!

sobolevn commented 4 years ago

Or should it? Let's leave it open for now. I will have to make a small research.

ruwaid4 commented 4 years ago

@sobolevn Should this rule be implemented? If not, could you recommend us an issue to work on? We have looked at most of them but aren't up to date on what should be implemented or not.

sobolevn commented 4 years ago

@ruwaid4 here you go: