Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2336
情歌与酒
情歌与酒 2020-12-05 04:52

I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary.

A few months ago I used this implementation: Python hashable

8条回答
  •  伪装坚强ぢ
    2020-12-05 05:23

    It appears I am late to post. Not sure if anyone else has come up with ideas. But here is my take on it. The Dict is immutable and hashable. I made it immutable by overriding all the methods, magic and otherwise, with a custom '_readonly' function that raises an Exception. This is done when the object is instantiated. To get around the problem of not being able to apply the values I set the 'hash' under '__new__'. I then I override the '__hash__'function. Thats it!

    class ImmutableDict(dict):
    
    _HASH = None
    
    def __new__(cls, *args, **kwargs):
        ImmutableDict._HASH = hash(frozenset(args[0].items()))
        return super(ImmutableDict, cls).__new__(cls, args)
    
    def __hash__(self):
        return self._HASH
    
    def _readonly(self, *args, **kwards):
        raise TypeError("Cannot modify Immutable Instance")
    
    __delattr__ = __setattr__ = __setitem__ = pop = update = setdefault = clear = popitem = _readonly
    

    Test:

    immutabled1 = ImmutableDict({"This": "That", "Cheese": "Blarg"})

    dict1 = {immutabled1: "Yay"}

    dict1[immutabled1]

    "Yay"

    dict1

    {{'Cheese': 'Blarg', 'This': 'That'}: 'Yay'}

提交回复
热议问题