generic object - moving toward PEP

Robert Brewer fumanchu at amor.org
Fri Nov 19 19:14:26 EST 2004


Steven Bethard wrote:
> So I thought I'd try to summarize a few things here and maybe we can 
> move toward filing a PEP.  I'm not really sure I'm the right 
> person to 
> champion it because, as I've mentioned, I usually eventually replace 
> generic objects with concrete classes, but I'm certainly 
> willing to do 
> some of the work writing it up, etc.  If you're interested in helping 
> me, let me know (off-list).
> 
> Some quotes from this thread:
> 
> Hung Jung Lu wrote:
>  > It seems odd that there is no standard generic object in Python.
> 
> Fernando Perez wrote:
>  > IPython has this fairly fancy Struct module, which is 
> yet-another-shot
>  > at the same thing.
> [snip]
>  > But if someone does add a fully functional contribution of 
> this kind,
>  > with enough bells and whistles to cover the more advanced 
> cases, I'd
>  > be +100 on that :)
> 
> Some arguments for a generic object:
> 
> (1) Allows a simple syntax for returning named results:
> 
>  >>> def f(x):
> ... 	return bunch(double=2*x, squared=x**2)
> ...
>  >>> y = f(10)
>  >>> y.double
> 20
>  >>> y.squared
> 100
> 
> (2) Allows simple representation of hierarchical data:
> 
>  >>> x = bunch(a=bunch(b=1, c=10), d=100)
>  >>> x.a.b
> 1
>  >>> x.d
> 100
> 
> Note that without a generic object class of some sort this would 
> probably be written as something like:
> 
>  >>> class C1(object):
> ... 	def __init__(self, a, d):
> ... 		self.a, self.d = a, d
> ... 		
>  >>> class C2(object):
> ... 	def __init__(self, b, c):
> ... 		self.b, self.c = b, c
> ... 		
>  >>> x = C1(a=C2(b=1, c=10), d=100)

No, it would be written:

>>> x = dict(a=dict(b=1, c=10), d=100)

I don't see anything bunch offers over dict() for this example. 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, while still
being able to use a simple, generic 'bunch' object--as soon as you need
both, you've outgrown "bunch".


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list