class attrdict

MonkeeSage MonkeeSage at gmail.com
Sat Mar 3 17:28:03 EST 2007


On Mar 3, 1:29 pm, a... at mac.com (Alex Martelli) wrote:
> It would be nice, yes, weren't it for the inevitable irregularity, one
> way or another, caused by the clash between attributes and items.

In thinking about it, I think this might fall under 'we're all
consenting adults here'. I mean, you can shadow the dict constructor
from the toplevel if you're so inclined (or don't know any better).
But you could make it harder to accidentally shadow builtin
attributes:

from warnings import warn
class attrdict(dict):
    __builtins__ = dir(dict)
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        for k, v in self.items():
            dict.__setattr__(self, str(k), v)
    def __setitem__(self, k, v):
        if k in self.__builtins__:
            warn('shadowing builtin attribute: %s' % k,
RuntimeWarning, 2)
        dict.__setitem__(self, k, v)
        dict.__setattr__(self, str(k), v)
    __setattr__ = __setitem__

a = attrdict([(1,2)], a=3, b=4)
a.update = 'test'

Regards,
Jordan




More information about the Python-list mailing list