generic object - moving toward PEP

Steven Bethard steven.bethard at gmail.com
Fri Nov 19 19:37:44 EST 2004


Robert Brewer wrote:
> Steven Bethard wrote:
>> >>> x = bunch(a=bunch(b=1, c=10), d=100)
>> >>> x.a.b
>>1
>> >>> x.d
>>100
[snip way to write this without a bunch class]
> 
> No, it would be written:
>
>>>>x = dict(a=dict(b=1, c=10), d=100)

I understand your point of course, but note that your code does not 
produced the desired behavior:

 >>> x = dict(a=dict(b=1, c=10), d=100)
 >>> x.a.b
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'dict' object has no attribute 'a'

Instead of having a class-like object, you (obviously) have nested dicts 
and therefore have to access them with [] (or the like):

 >>> x['a']['b']
1

Note that this is what point 3 was about: "Allows simple conversion from 
dict-style access to attribute access".

Of course, whether or not you want attribute access instead of []-style 
access is a design decision.  Heck, I could avoid ever writing a class 
again by just using dicts instead -- forcing all the users of my 
"classes" to use []-style access instead of attribute-style access.  The 
power is there -- that's basically what __dict__ is doing anyway, right? 
  It's not something *I* would do, but it's a design decision to be made 
nonetheless.

Providing a 'bunch' (or equivalent) class allows one to make this design 
decision (attribute access vs. []-style access) without having to 
declare a class every time.

> If you're returning a value that needs to be unpacked positionally, use
> a tuple. If it needs to be unpacked lexically, use a dict. I have yet
> to see an example where it's advantageous to support both

This doesn't really have anything to do with the proposal.  We're not 
suggesting a named-tuple here (though see a recent (current?) thread 
that is).  The 'bunch' class, or whatever you want to call it, is 
intended to support dotted-attribute access, in contrast to dict's 
sequential [] access.

Steve



More information about the Python-list mailing list