MonkeeSage <[EMAIL PROTECTED]> wrote: > On Mar 3, 1:29 pm, [EMAIL PROTECTED] (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'
Besides missing the warning in the __init__, this also has pretty weird behavior whenever subject to a .pop, .update, .setdefault, del of either item or attr, etc, etc: the attributes and items "get out of sync" (and, catching each and every mutating-method to keep the separate dicts of items and attrs in perfect sync is somewhat of a nightmare). If the consenting adults in question WANT totally murky, irregular, buggy behavior hiding under every corner -- why are they using Python in the first place? It's so much easier to make such utter messes in other languages, after all. It's impossible to make something foolproof, because fools are so ingenious; Python tends to keep them at bay by cultural forces (a strong collective bias towards simplicity, regularity, correctness). The neverending quest to confuse attributes and items (inevitably leading to complications, irregularity, and bugs) is better pursued in other languages -- just about ANY other language except Python. Alex -- http://mail.python.org/mailman/listinfo/python-list