是否可以在创建后“冻结”python dict,以便无法向其中添加新键?只能更改现有的键值。
如果没有,您如何知道何时更改现有键值对以及何时添加新键值对?
是否可以在创建后“冻结”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)
>>> 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
请注意,您可能还想覆盖其他方法,包括__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'})
或者只是在一行中,没有对原始字典的引用:
>>> 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
这对于“香草”字典是不可能的。您可能想要子类化collections.MutableMapping
. . .
未经测试的代码如下
class FrozenKeyDict(collections.MutableMapping):
"""Mapping which doesn't allow keys to be added/deleted.
It does allow existing key/value pairs to be modified.
"""
def __init__(self, *args, **kwargs):
self._frozen = False
self._dict = {}
super(FrozenKeyDict, self).__init__(*args, **kwargs)
self._frozen = True
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
if self._frozen and key not in self._dict:
raise KeyError('must be one of %s' % list(self))
self._dict[key] = value
def __delitem__(self, key):
# modify to suit your needs ...
raise KeyError('Removing keys not supported')
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)