astral-sh / astral-sh/ruff

Default for dict.get(). Possible new rule

Open
#12,486 2 comments 1 reaction 0 assignees View on GitHub
rule type-inference
Dominant language
Rust
Stars
49.7k
Forks
2.4k
Avg merge
2d 1h
Merged PRs (30d)
458

Description

Hi,
I am not fully sure, so, it's more about starting discussion, but have a feeling it might be good to have a rule for such cases.
There is a standard way to get default while getting key's value from a dictionary:
```
mydict.get("key_name", default_value)
```
and it works fine in most of the cases, but it's easy to forget that it will set default only if key is not present in dict. If key is present and have some empty value like `None` get() will not return default:
```
>>> mydict = dict(key=None)
>>> print(mydict.get("key", 0))
None
```
It's correct and [documented](https://docs.python.org/3/library/stdtypes.html#dict.get) behaviour, but can confuse, sometimes correct way is:
```
mydict.get("key") or 0
```
but probably linter can't know which way correct in particular cases.

Contributor guide

Open the contributing guide

Research direction

Start with the proposed dict.get() and `mydict.get("key") or 0` examples, then review the linked Python dict.get documentation. The issue does not name a Ruff file, test, or settled rule; work is not ready until the rule's intended behavior and completion criteria are agreed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.