generic object - moving toward PEP
Dieter Maurer
dieter at handshake.de
Sun Nov 21 13:30:33 EST 2004
Steven Bethard <steven.bethard at gmail.com> writes on Fri, 19 Nov 2004 21:38:14 GMT:
> ...
> 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
> ...
> (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
How about:
class bunch:
def __init__(self, d__=None, **kw):
d = self.__dict__
if d__ is not None: d.update(d__)
d.update(kw)
You can drop the "d__" magic, when you do not need direct
"dict --> bunch" conversion (of the form "bunch(dict)")
but use a special method ("frommapping") for this.
--
Dieter
More information about the Python-list
mailing list