[Python-ideas] Support other dict types for type.__dict__
Ronny Pfannschmidt
Ronny.Pfannschmidt at gmx.de
Fri Feb 24 09:07:31 CET 2012
On 02/24/2012 01:27 AM, Victor Stinner wrote:
>> And you can't use __slots__ because...?
>
> Hum, here is an example:
> ---
note untested, since written in mail client:
class Enum(object):
__slots__ = ("_data",)
_data = WriteOnceDescr('_data') # left as exercise
def __init__(self, **kw):
self._data = frozendict(kw)
def __getattr__(self, key):
try:
return self._data[key]
except KeyError:
raise AttributeError(key)
> def Enum(**kw):
> class _Enum(object):
> __slots__ = list(kw.keys())
> def __new__(cls, **kw):
> inst = object.__new__(cls)
> for key, value in kw.items():
> setattr(inst, key, value)
> return inst
> return _Enum(**kw)
>
> components = Enum(red=0, green=1, blue=2)
> print(components.red)
> components.red=2
> print(components.red)
> components.unknown=10
> ---
>
> components.unknown=10 raises an error, but not components.red=2.
> __slots__ denies to add new attributes, but not to modify existing
> attributes.
>
> The idea of using a frozendict is to deny the modification of an
> attribute value after the creation of the object. I don't see how to
> use __slots__ to implement such constraints.
>
> Victor
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
More information about the Python-ideas
mailing list