Alan Green web.mail at
Thu Oct 18 02:29:11 CEST 2001


Neat code. Looks like it has been through a few iterations. Thanks for
posting it.

I used this on our company internal mailing as an interesting example
of several Python features:

1. def fn(*arg) - to collect an arbitrary argument list. (twice!)
2. Use of setattr() rather than stuffing things into an instance's
3. An exception raised with a very neat error message. (Makes
debugging simpler.
4. Defining a class inside a function - creates a new class object
each time the function is run.
5. The class object returned by the function has no public name, but
can still be used to instantiate instances. Question to think about:
should the returned class be assigned to a variable with an initial
Uppercase letter?




kragen at (Kragen Sitaker) wrote in message news:<fVYy7.38371$6i7.4098701 at>...

[snip, snip]

> # -- Kragen Sitaker, 2001-10-16
> def defstruct(*fields):
>     class Struct:
>         def __init__(self, *contents):
>             if len(contents) != len(self.structfields):
>                 raise TypeError, (
>                     "wrong number of arguments: expected %d %s, got %d" %
>                     (len(self.structfields),
>                      repr(self.structfields),
>                      len(contents)))
>             for fieldnum in range(len(contents)):
>                 setattr(self, self.structfields[fieldnum], contents[fieldnum])
>     Struct.structfields = fields
>     return Struct    
[snip, snip]

More information about the Python-list mailing list