Define a python dictionary with immutable keys but mutable values

前端 未结 3 1686
陌清茗
陌清茗 2021-01-04 10:04

Well, the question is in the title: how do I define a python dictionary with immutable keys but mutable values? I came up with this (in python 2.x):

class Fi         


        
3条回答
  •  不知归路
    2021-01-04 10:30

    How you prevent someone from adding new keys depends entirely on why someone might try to add new keys. As the comments state, most dictionary methods that modify the keys don't go through __setitem__, so a .update() call will add new keys just fine.

    If you only expect someone to use d[new_key] = v, then your __setitem__ is fine. If they might use other ways to add keys, then you have to put in more work. And of course, they can always use this to do it anyway:

    dict.__setitem__(d, new_key, v)
    

    You can't make things truly immutable in Python, you can only stop particular changes.

提交回复
热议问题