wemake-python-styleguide icon indicating copy to clipboard operation
wemake-python-styleguide copied to clipboard

Enforce using `.setdefault()`

Open sobolevn opened this issue 5 years ago • 5 comments

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.

sobolevn avatar Dec 19 '19 19:12 sobolevn

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

adambenali avatar Feb 26 '20 08:02 adambenali

Yes, thank you!

sobolevn avatar Feb 26 '20 09:02 sobolevn

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

sobolevn avatar Feb 26 '20 09:02 sobolevn

@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.

ruwaid4 avatar Apr 03 '20 12:04 ruwaid4

@ruwaid4 here you go:

  • https://github.com/wemake-services/wemake-python-styleguide/issues/864
  • https://github.com/wemake-services/wemake-python-styleguide/issues/1025
  • https://github.com/wemake-services/wemake-python-styleguide/issues/1239

sobolevn avatar Apr 03 '20 14:04 sobolevn