class attrdict
Alex Martelli
aleax at mac.com
Sat Mar 3 00:03:10 EST 2007
MonkeeSage <MonkeeSage at gmail.com> wrote:
> On Mar 2, 9:25 pm, a... at mac.com (Alex Martelli) wrote:
> > The problem is mostly that, given an instance a of attrdict, whether you
> > can call (e.g.) a.update(foo) depends on whether you ever set
> > a['update'], making the whole program extremely fragile -- a very high
> > price to pay for some modest amount of syntax sugar.
>
> How about something like...
>
> class attrdict(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):
> dict.__setitem__(self, k, v)
> dict.__setattr__(self, str(k), v)
> __setattr__ = __setitem__
Same problem: after x=attrdict(), x.update(foo) will work for a while,
then suddenly stop working after some innocuous loop such as:
for bah in yech: x[bah] = 23
when one of the items in yech just happens to be the word 'update'
(similar issues with words such as 'get', 'pop', 'clear', etc, etc).
Miscegenation between attributes and items *inevitably* sucks.
Alex
More information about the Python-list
mailing list