[Python-ideas] Support other dict types for type.__dict__
aquavitae69 at gmail.com
Sun Feb 26 10:42:54 CET 2012
On Feb 26, 2012 10:27 AM, "Simon Sapin" <simon.sapin at kozea.fr> wrote:
> Le 24/02/2012 00:34, Victor Stinner a écrit :
>> I'm trying to create read-only objects using a "frozendict" class.
>> frozendict is a read-only dict. I would like to use frozendict for the
>> class dict using a metaclass, but type.__new__() expects a dict and
>> creates a copy of the input dict.
>> I would be nice to support custom dict type: OrderedDict and
>> frozendict for example. It looks possible to patch CPython to
>> implement this feature, but first I would like first to know your
>> opinion about this idea:-)
> Combining ideas from other messages in this thread: would this work?
> 1. Inherit from frozendict
> 2. Define a __getattr__ that defers to frozendict.__getitem__
> 3. Use an empty __slots__ so that there is no "normal" instance attribute.
> Thinking about it a bit more, it’s probably the same as having a normal
> __dict__ and raising in __setattr__ and __delattr__. Isn’t this how you
> implement frozendict? (Raise in __setitem__, __delitem__, update, etc.)
> Simon Sapin
> Python-ideas mailing list
> Python-ideas at python.org
Using frozendict, and especially inheriting from it sounds unnecessarily
complicated to me. A simple class which doesn't allow changes to instance
attributes could be implemented something like this:
def __setattr__(self, attr, value):
def __delattr__(self, attr):
Or, if you're worried about changes to the class attributes, you could do
basically the same thing using a metaclass (python 2.7 syntax):
def __setattr__(cls, attr, value):
if attr in cls.__dict__ or '__done__' in cls.__dict__:
type.__setattr__(cls, attr, value)
def __delattr__(cls, attr):
__metaclass__ = FinalMeta
value = 3
__done__ = True # There may be a neater way to do this...
Each of the following examples will fail:
>>> Three.another_value = 4
>>> Three.value = 4
>>> del Three.value
>>> three = Three(); three.value = 4
Actually, I think this is quite a nice illustration of what can be done
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas