Skip to content

Default Get

Sourcery refactoring id: default-get


Simplify dictionary access by using the default get method


def pick_hat(available_hats: Dict[Label, Hat]):
    if self.favourite_hat in available_hats:
        hat_to_wear = available_hats[self.favourite_hat]
        hat_to_wear = NO_HAT
    return hat_to_wear


def pick_hat(available_hats: Dict[Label, Hat]):
    hat_to_wear = available_hats.get(self.favourite_hat, NO_HAT)
    return hat_to_wear


We often want to pick something from a dictionary if the key is present, or use a default value if it isn't.

A useful shortcut is that Python dictionaries have a get() method which lets you set a default value using the second parameter.

This has slimmed the code down and removed some duplication. A point to note is that if you don't pass in a default value to get() it will use None.