dan*_*vic 9 python dictionary immutability keyvaluepair
是否有可能在创建后"冻结"python dict,以便无法为其添加新密钥?只能更改现有的键值.
如果没有,您如何知道何时更改现有的键值对,以及何时添加新的键值对?
也许是这样的:
class FreezableDict (dict):
__frozen = False
def freeze (self):
self.__frozen = True
def __setitem__ (self, key, value):
if self.__frozen and key not in self:
raise ValueError('Dictionary is frozen')
super().__setitem__(key, value)
Run Code Online (Sandbox Code Playgroud)
>>> x = FreezableDict({'foo': 'bar', 'baz': 'bla'})
>>> x
{'baz': 'bla', 'foo': 'bar'}
>>> x['asdf'] = 'fdsa'
>>> x
{'asdf': 'fdsa', 'baz': 'bla', 'foo': 'bar'}
>>> x.freeze()
>>> x['hello'] = 'world'
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
x['hello'] = 'world'
File "<pyshell#13>", line 8, in __setitem__
raise ValueError('Dictionary is frozen')
ValueError: Dictionary is frozen
Run Code Online (Sandbox Code Playgroud)
请注意,您可能要覆盖其他方法也包括__delitem__,update,setdefault,pop,和popitem,因为它们都可以修改的字典.
如果您对完全锁定字典感兴趣,可以使用types.MappingProxyType它为字典提供只读视图.一旦创建了普通字典,就可以创建它的映射代理,它只是没有任何赋值/更新功能.您也可以删除对原始字典的任何引用(映射将保留一个),以防止它被用于进一步更新它:
>>> x = {'foo': 'bar'}
>>> y = types.MappingProxyType(x)
>>> y
mappingproxy({'foo': 'bar'})
>>> x['baz'] = 'bla'
>>> y
mappingproxy({'baz': 'bla', 'foo': 'bar'})
>>> y['hello'] = 'world'
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
y['hello'] = 'world'
TypeError: 'mappingproxy' object does not support item assignment
>>> del x
>>> y
mappingproxy({'baz': 'bla', 'foo': 'bar'})
Run Code Online (Sandbox Code Playgroud)
或者只是在一行中,没有引用原始字典:
>>> x = types.MappingProxyType({'foo': 'bar', 'baz': 'bla'})
>>> x
mappingproxy({'baz': 'bla', 'foo': 'bar'})
>>> x['hello'] = 'world'
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
x['hello'] = 'world'
TypeError: 'mappingproxy' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)