[Python-Dev] Add a frozendict builtin type (original) (raw)
Serhiy Storchaka storchaka at gmail.com
Thu Mar 1 14:44:18 CET 2012
- Previous message: [Python-Dev] Add a frozendict builtin type
- Next message: [Python-Dev] Add a frozendict builtin type
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
01.03.12 11:11, Victor Stinner написав(ла):
You can redefine dict.setitem. Ah? It doesn't work here.
dict.setitem=lambda key, value: None Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'dict'
Hmm, yes, it's true. It was too presumptuous of me to believe that you have not considered such simple approach.
But I will try to suggest another approach. frozendict
inherits from
dict
, but data is not stored in the parent, but in the internal
dictionary. And even if dict.setitem is used, it will have no
visible effect.
class frozendict(dict): def init(self, values={}): self._values = dict(values) def getitem(self, key): return self._values[key] def setitem(self, key, value): raise TypeError ("expect dict, got frozendict") ...
a = frozendict({1: 2, 3: 4}) a[1] 2 a[5] Traceback (most recent call last): File "", line 1, in File "", line 5, in getitem KeyError: 5 a[5] = 6 Traceback (most recent call last): File "", line 1, in File "", line 7, in setitem TypeError: expect dict, got frozendict dict.setitem(a, 5, 6) a[5] Traceback (most recent call last): File "", line 1, in File "", line 5, in getitem KeyError: 5
- Previous message: [Python-Dev] Add a frozendict builtin type
- Next message: [Python-Dev] Add a frozendict builtin type
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]