Skip to content

Instantly share code, notes, and snippets.

@victory-sokolov
Created November 3, 2021 19:26
Show Gist options
  • Save victory-sokolov/49c5b0451d422aa25ab35f90ab8dd717 to your computer and use it in GitHub Desktop.
Save victory-sokolov/49c5b0451d422aa25ab35f90ab8dd717 to your computer and use it in GitHub Desktop.
Python immutable dictionary
# reference: https://stackoverflow.com/questions/11014262/how-to-create-an-immutable-dictionary-in-python?utm_source=pocket_mylist
class imdict(dict):
def __hash__(self):
return id(self)
def _immutable(self, *args, **kws):
raise TypeError('object is immutable')
__setitem__ = _immutable
__delitem__ = _immutable
clear = _immutable
update = _immutable
setdefault = _immutable
pop = _immutable
popitem = _immutable
post = imdict({
'title': 'My title',
'body': 'Body of the post'
})
post['title'] = 'New title' # TypeError: object is immutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment