[Python-Dev] Add a frozendict builtin type
Guido van Rossum
guido at python.org
Fri Mar 2 01:50:06 CET 2012
On Thu, Mar 1, 2012 at 4:39 PM, Victor Stinner <victor.stinner at gmail.com> wrote:
> Le 01/03/2012 19:07, Guido van Rossum a écrit :
>
>> What other use cases are there?
>
>
> frozendict could be used to implement "read-only" types: it is not possible
> to add or remove an attribute or set an attribute value, but attribute value
> can be a mutable object. Example of an enum with my type_final.patch
> (attached to issue #14162).
>
>>>> class Color:
> ... red=1
> ... green=2
> ... blue=3
> ... __final__=True
> ...
>>>> Color.red
> 1
>>>> Color.red=2
>
> TypeError: 'frozendict' object does not support item assignment
>>>> Color.yellow=4
>
> TypeError: 'frozendict' object does not support item assignment
>>>> Color.__dict__
> frozendict({...})
>
> The implementation avoids the private PyDictProxy for read-only types,
> type.__dict__ gives directly access to the frozendict (but
> type.__dict__=newdict is still blocked).
>
> The "__final__=True" API is just a proposition, it can be anything else,
> maybe a metaclass.
>
> Using a frozendict for type.__dict__ is not the only possible solution to
> implement read-only types. There are also Python implementation using
> properties. Using a frozendict is faster than using properties because
> getting an attribute is just a fast dictionary lookup, whereas reading a
> property requires to execute a Python function. The syntax to declare a
> read-only class is also more classic using the frozendict approach.
I think you should provide stronger arguments in each case why the
data needs to be truly immutable or read-only, rather than just using
a convention or an "advisory" API (like __private can be circumvented
but clearly indicates intent to the reader).
--
--Guido van Rossum (python.org/~guido)
More information about the Python-Dev
mailing list