generic object implementation

Steven Bethard steven.bethard at gmail.com
Mon Nov 22 02:27:36 EST 2004


Bengt Richter wrote:
> 
> UIAM 'bunch' already has a related meaning from c.l.py past (approx the first
> three lines of your class), so how about 'gob' ? ;-)

Yeah, the intent is basically to provide that 3-liner.  Could be that's 
all that should be in the class...  It wouldn't cover all my use cases, 
but I'd certainly be happier with that than nothing.

> I dunno, begins to look more like a dict with getattr access substituted for __getitem__
> than a primitive generic object...

Yeah, the idea is to provide getattr access instead of __getitem__ -- 
that's basically what the original 3-liner does too.  For my uses, I 
don't think I'd ever want any of __len__, __iter__, __contains__, items, 
keys, values, etc. but I wasn't the only one who seemed interested in 
the idea...  The pyparsing code in particular might benefit from 
something like the frommapping method (and I know I could use it to 
convert XML DOM into nested objects)...

>  >>> class dbunch(dict):
>  ...     def __metaclass__(name, bases, cdict):
>  ...         cdict.update(dict.__dict__)
>  ...         cdict['__getattr__'] = cdict['__getitem__']
>  ...         cdict['__setattr__'] = cdict['__setitem__']
>  ...         cdict['__delattr__'] = cdict['__delitem__']
>  ...         def raiseunsub(*ignore): raise TypeError, 'unsubscriptable object'
>  ...         cdict['__getitem__'] = raiseunsub
>  ...         cdict['__setitem__'] = raiseunsub
>  ...         cdict['__delitem__'] = raiseunsub
>  ...         return type(name, bases, cdict)
>  ...

Interesting approach here.  I hadn't thought of going this way.  While I 
hadn't planned on supporting the whole mapping interface, this would 
certainly be an easy way to do so.  I'll probably wait for a little more 
feedback to see what the others who were interested want to use these 
for...  If people have good use cases for keys, items, etc. this is 
probably the right answer...

> It the hope for a lean representation for small numbers
> of items?

Not exactly sure what you mean by lean...

All the use cases I have for it only care about 'obj.x' type access, and 
don't really use any of the other container type methods.  So in my 
case, __init__, __eq__, __repr__, update and frommapping do pretty much 
everything I want...  If this is true for everyone else's use cases, I'd 
rather not "pollute" the class with a bunch of dict methods...  But I'm 
certainly willing to be persuaded that other methods are also essential.

Steve



More information about the Python-list mailing list