dynamism

Oren Tirosh oren-py-l at hishome.net
Tue Sep 10 11:23:32 CEST 2002


On Mon, Sep 09, 2002 at 11:45:35PM -0400, Raymond Hettinger wrote:
> >>> class BetterAttrDict(dict):
>  def __getattr__(self, key):
>   return dict.__getitem__(self, key)
> 
> 
> >>> bad = BetterAttrDict({'a': 1, 'b':2})
> >>> bad.a
> 1
> >>> bad.b
> 2

class EvenBetterAttrDict(dict):
    def __init__(self, d={}, **kw):
        """ Initialize from a mapping or using keyword=value pairs """
        dict.update(self, d)
        dict.update(self, kw)

    def __getattr__(self, key):
        """ Return dictionary items as members """
        return dict.__getitem__(self, key)

    def __setattr__(self, key, value):
        """ Set dictionary items as members """
        try:
            dict.__getattribute__(self, key)
        except AttributeError:
            dict.__setitem__(self, key, value)
        else:
            dict.__setattr__(self, key, value)

    def __delattr__(self, key):
        """ Delete dictionary items as members """
        try:
            dict.__getattribute__(self, key)
        except AttributeError:
            dict.__delitem__(self, key)
        else:
            dict.__delattr__(self, key)

    def __repr__(self):
        """ Display as a constructor call with keyword arguments """
        items = dict.items(self)
        items.sort()
        return "%s(%s)" % (
            self.__class__.__name__,
            ", ".join(
                ["%s=%s" % (k,`v`) for k,v in items]
            )
        )

    def __members__(self):
        """ Support dir(), rlcompleter attribute completion """
        return dict.keys(self)

    __members__ = property(__members__)



>>> class person(EvenBetterAttrDict): pass
...
>>> p = person(name='Oren', born=1971)
>>> p
person(born=1971, name='Oren')
>>> p.likes ='Chocolate!'
>>> p
person(born=1971, likes='Chocolate!', name='Oren')
>>>

Overkill? perhaps.

	Oren





More information about the Python-list mailing list