structs in python

Fredrik Lundh fredrik at pythonware.com
Sun Jul 14 06:53:05 EDT 2002


Paul Magwene wrote:

> > What if a syntax like the following were permitted:
> >>>> p = ( .x = 10, .y = 11, .color = 'blue')
>
> I often find myself doing something similar to the following (usually
> when I want to return multiple things from a function)
>
> >>> class Struct:
> ...     pass
> ...
> >>> p = Struct()
> >>> p.x = 10
> >>> p.y = 11
> >>> p.color = 'blue'
>
> That's slightly more verbose than you're proposed syntax but doesn't
> usually feel to onerous (especially since you only have to declare the
> Struct class once).

the more reason to "do the right thing", right? ;-)

    class Struct:
        def __init__(self, **kw):
            self.__dict__.update(kw)

> If you like everything on one line you could do:
>
> >>> p = Struct(); p.x = 10; p.y = 11; p.color = 'blue'

    p = Struct(x=10, y=11, color='blue')

</F>





More information about the Python-list mailing list