Dynamically create a class (or class instance) and its attributes?

Peter Otten __peter__ at web.de
Tue Jul 27 12:26:03 CEST 2004


Robert Oschler wrote:

> To make the syntax easier and clearer, I would like to create a Python
> class instance that would allow me to access the fields in the MySQL row
> as attributes of a class created dynamically from the row structure. For
> example:
> 
> employee_name = ez_sqlrow.empname

Here is one way:

import itertools

class Record:
    def __init__(self, row):
        assert len(row) == len(self.names)
        self._row = row
    def __getitem__(self, index):
        return self._row[index]
    def __setitem__(self, index, value):
        self._row[index] = value
    def __iter__(self):
        return itertools.izip(self.names, self._row)
    def __repr__(self):
        return "%s(%s)"  % (self.__class__.__name__,
            ", ".join(["%s=%r" % nv for nv in self]))

def makeProperty(index):
    def get(self):
        return self[index]
    def set(self, value):
        self[index] = value
    return property(get, set)

def makeClass(classname, fieldnames, Base=Record):
    class Record(Base):
        names = fieldnames
    Record.__name__ = classname

    for index, name in enumerate(fieldnames):
        setattr(Record, name, makeProperty(index))
    return Record

if __name__ == "__main__":
    Person = makeClass("Person",  ["firstname", "lastname", "email"])
    r = Person(["Robert", "Oschler", "not provided"])
    print r.firstname
    r.email = "rosch at no.spam"
    print r.email
    print "%s %s" % tuple(r[:2])
    print r

which is actually a variant of something I posted a few days ago. Or you go
with SQLObject.(Am I repeating myself? Am I repeating myself :-)

Peter





More information about the Python-list mailing list