object as bunch (WAS Re: End of file)

Steven Bethard steven.bethard at gmail.com
Mon Oct 11 18:13:22 CEST 2004


Alex Martelli <aleaxit <at> yahoo.com> writes:
> 
> If an object() could be used as a Bunch I do think it would be
> reasonably common.  But it can't, so I insist that its role as
> sentinel/placeholder is the only possibility.

Anyone know what the design goal was that caused object not to be written to 
be used as a Bunch?

I'm not suggesting that I'd want to be able to set attributes from outside the 
class -- the fact that x23.foo = 23 is an AttributeError if x23 does not have 
a foo attribute is a Good Thing, IMHO -- but I can see that a **kwds 
constructor like dict() has might be useful:

>>> o = object(foo1=None, foo2=23)
>>> o.foo1
>>> o.foo2
23
>>> o.foo3 = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute 'foo3'

If object was a Bunch, you could also set the fields of a class in the call to 
object's __init__.  

>>> class C(object):
...     def __init__(self, foo23, foo57=None):
...             super(C, self).__init__(foo23=foo23, foo57=foo57)
...
>>> c = C(1)
>>> c.foo57
>>> c.foo23
1

Don't know if the fields behavior here really gains you anything, but it would 
be another side effect of object being a Bunch.

I have wanted from time to time to have a Bunch object.  Of course it's only 3 
lines of code to roll your own...  But I wouldn't mind hearing about the 
reasoning behind making object as it is...

Steve




More information about the Python-list mailing list