Created
February 8, 2017 09:01
-
-
Save barahilia/f34482c8f98306362102d77d358a496a to your computer and use it in GitHub Desktop.
A defaultdict that can be frozen after which it will not add new missing keys but still return a default object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
class freezable_defaultdict(dict): | |
def __init__(self, default_factory, *args, **kwargs): | |
self.frozen = False | |
self.default_factory = default_factory | |
super(freezable_defaultdict, self).__init__(*args, **kwargs) | |
def __missing__(self, key): | |
if self.frozen: | |
return self.default_factory() | |
else: | |
self[key] = value = self.default_factory() | |
return value | |
def freeze(self): | |
self.frozen = True |
Another alternative is to set defaultdict
default_factory
to None. This will raise an error instead of adding a new default. See also https://stackoverflow.com/a/13465745 and https://docs.python.org/3/library/collections.html#collections.defaultdict
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative is to use
defaultdict.get(key, default_value)
, which doesn't add a new entry for a missing key indefaultdict