Use dict.get with default instead of if-else

Python pattern

Join multiple with statements into a single one. Rule SIM401 from flake8-simplify.

Caveat: the transformation is not run if either $key or $default have a function call, as they would be called a different number of times in the new code.


Apply with the Grit CLI
grit apply dict_get_instead_of_if_else_block

Replace if-else with dict.get()

BEFORE
if "my_key" in example_dict:
    thing = example_dict["my_key"]
else:
    thing = "default_value"


# Left as is

if f() in example_dict:
    thing = example_dict[f()]
else:
    thing = "default_value"

if "my_key" in example_dict:
    thing = example_dict["my_key"]
else:
    thing = "default_value" + f()

if "name" in d:
    name = d[name]
else:
    name = "foo"

if "name" in d:
    name = d["name"]
else:
    surname = "foo"
AFTER
thing = example_dict.get("my_key", "default_value")


# Left as is

if f() in example_dict:
    thing = example_dict[f()]
else:
    thing = "default_value"

if "my_key" in example_dict:
    thing = example_dict["my_key"]
else:
    thing = "default_value" + f()

if "name" in d:
    name = d[name]
else:
    name = "foo"

if "name" in d:
    name = d["name"]
else:
    surname = "foo"