generic object - moving toward PEP

Steven Bethard steven.bethard at gmail.com
Fri Nov 19 16:38:14 EST 2004


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)

Because the generic object version requires only one class (called 
'bunch' above), only this class would be needed for 
unpickling/unserializing.  If the generic object class was easily 
available (e.g. in the standard library), this could simplify the 
unpickling process somewhat.

(3) Allows simple conversion from dict-style access to attribute access:

 >>> d = {'a':2, 'b':4, 'c':16, 'd':256}
 >>> d['a'], d['d']
(2, 256)
 >>> b = bunch(**d)
 >>> b.a, b.d
(2, 256)

This could actually be supported recursively, if that seems useful:

 >>> d = {'a':2, 'b':4, 'c':{'d':16, 'e':256}}
 >>> b = bunch.frommapping(d)
 >>> b.c.d
16



I think that's most of the arguments I saw on the thread.  If anyone 
else has arguments for/against adding a generic object type to the 
standard lib, now's the time to bring them up. =)

Steve



More information about the Python-list mailing list