Skip to content

Instantly share code, notes, and snippets.

@genadyp
Forked from glyphobet/immutabledict.py
Created June 10, 2021 08:47
Show Gist options
  • Save genadyp/efd97946a21114d08b482081e51ce75b to your computer and use it in GitHub Desktop.
Save genadyp/efd97946a21114d08b482081e51ce75b to your computer and use it in GitHub Desktop.
Immutable dictionary in Python
class ImmutableDict(dict):
def __setitem__(self, key, value):
raise TypeError("%r object does not support item assignment" % type(self).__name__)
def __delitem__(self, key):
raise TypeError("%r object does not support item deletion" % type(self).__name__)
def __getattribute__(self, attribute):
if attribute in ('clear', 'update', 'pop', 'popitem', 'setdefault'):
raise AttributeError("%r object has no attribute %r" % (type(self).__name__, attribute))
return dict.__getattribute__(self, attribute)
def __hash__(self):
return hash(tuple(sorted(self.iteritems())))
def fromkeys(self, S, v):
return type(self)(dict(self).fromkeys(S, v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment