question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Enforce using `.setdefault()`

See original GitHub issue

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.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:5 (5 by maintainers)

github_iconTop GitHub Comments

0reactions
ruwaid4commented, Apr 3, 2020

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

Use cases for the 'setdefault' dict method - Stack Overflow
The solution is to use setdefault() as the last step of saving the computed composite member -- if another has already been saved...
Read more >
Python dict setdefault - Linux Hint
The setdefault() function is used to set a default key in the key : value pair of the dictionary. It takes 2 parameters,...
Read more >
Python Dictionary setdefault() method with Examples
Python setdefault() method is used to set default value to the key. It returns value, if the key is present. Otherwise it insert...
Read more >
Python Dictionary setdefault() Method - GeeksforGeeks
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default...
Read more >
Python setdefault Function| Python Dictionary - Scaler Topics
If the key is not in the dictionary and default_value is specified, then the Python setdefault() function will return the default_value. Working ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found