Skip to content

[SIM121] Use ".get" instead of "if X in dict: dict[X]" #50

@MartinThoma

Description

@MartinThoma

Explanation

The get(key, default_fallback=None) method of a dictionary is often overlooked. It provides a clear interface that every Python developer should know.

Example

# Bad
name = "some_default"
if "some_key" in some_dict:
    name = some_dict["some_key"]

# Good
name = some_dict.get("some_key", "some_default")

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions