Default Get
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: default-get
Section titled “Sourcery refactoring id: default-get”Description:
Section titled “Description:”Simplify dictionary access by using the default get method
Before:
Section titled “Before:”def pick_hat(available_hats: Dict[Label, Hat]): if self.favourite_hat in available_hats: hat_to_wear = available_hats[self.favourite_hat] else: hat_to_wear = NO_HAT return hat_to_wearAfter:
Section titled “After:”def pick_hat(available_hats: Dict[Label, Hat]): hat_to_wear = available_hats.get(self.favourite_hat, NO_HAT) return hat_to_wearExplanation:
Section titled “Explanation:”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.