Factory for Struct-like classes

Marc Christiansen usenet at solar-empire.de
Wed Aug 13 13:54:33 EDT 2008


eliben <eliben at gmail.com> wrote:
> Hello,
> 
> I want to be able to do something like this:
> 
> Employee = Struct(name, salary)
> 
> And then:
> 
> john = Employee('john doe', 34000)
> print john.salary
> 
> Basically, Employee = Struct(name, salary) should be equivalent to:
> 
> class Employee(object):
>  def __init__(self, name, salary):
>    self.name = name
>    self.salary = salary
> 
> Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html)
> does this. I suppose it can be done with 'exec', but is there a more
> Pythonic way ?
> 
> Thanks in advance

I have some old code laying around which should do what you want. It was
originally written by Kragen Sitaker in 2001-10-16 and is public domain.

def defstruct(*fields):
    class Struct(object):
        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 field, content in zip(self.structfields, contents):
                setattr(self, field, content)
    Struct.structfields = fields
    return Struct

Use:
Employee = defstruct("name", "salary")
john = Employee('john doe', 34000)
print john.salary

Marc



More information about the Python-list mailing list