Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@barahilia barahilia commented Jan 9, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment