[Python-Dev] Add a frozendict builtin type

Victor Stinner victor.stinner at gmail.com
Thu Mar 1 15:49:29 CET 2012


> 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")
>      ...

I would like to implement frozendict in C to be able to pass it to
PyDict_GetItem(), PyDict_SetItem() and PyDict_DelItem(). Using such
Python implementation, you would get surprising result:

d = frozendict()
dict.__setitem__(d, 'x', 1) # this is what Python does internally when
it expects a dict (e.g. in ceval.c for __builtins__)
'x' in d => False

(Python is not supposed to use the PyDict API if the object is a dict
subclass, but PyObject_Get/SetItem.)

Victor


More information about the Python-Dev mailing list