[Python-Dev] Add a frozendict builtin type (original) (raw)

Victor Stinner victor.stinner at gmail.com
Fri Mar 2 01:39:32 CET 2012


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.

Victor



More information about the Python-Dev mailing list