Created
November 3, 2021 19:26
-
-
Save victory-sokolov/49c5b0451d422aa25ab35f90ab8dd717 to your computer and use it in GitHub Desktop.
Python immutable dictionary
This file contains hidden or 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
# 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