Skip to content

Instantly share code, notes, and snippets.

@barahilia
Created February 8, 2017 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barahilia/f34482c8f98306362102d77d358a496a to your computer and use it in GitHub Desktop.
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
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
@barahilia
Copy link
Author

An alternative is to use defaultdict.get(key, default_value), which doesn't add a new entry for a missing key in defaultdict

@boxydog
Copy link

boxydog commented Feb 8, 2023

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