Dynamically creating attributes and methods

Alex Martelli aleax at aleax.it
Wed Oct 29 18:22:05 EST 2003


 user at domain.invalid wrote:

> Hi,
> 
> I'm writing a DBI for my company's database.
> I will have one class for each of the tables
> in the database.
> 
> I would then like each class, once instantiated,
> to be able to read the field list from it's table,
> and create properties based on each field, with
> get/set methods created for accessing.

OK -- I think you can find already-made Python
modules that do such kinds of jobs, but still,
it's probably OK to do the job yourself, too.

It is not clear to me if you want to regenerate
all the classes and their attributes/properties
dinamycally every time your program starts, and
why -- generating Python source code once, then
importing it on each run (regenerating the source,
perhaps automatically, if and when you determine
the database's schema has changed.

I assume the source-generation approach is clear
to you and will sketch how attack the "rebuild
dynamically each time the program starts" one.


> The get/set methods could be the same for every
> field, provided that I can determine the name
> of the field(property) being accessed.

Sure, and that's the key idea -- use a closure.

> Given a field name such as 'phone', how can I
> give the class a home property, and then attach
> that property to the get/set methods on the fly?

I'm not sure what "a home property" is.  In
context it would seem to make more sense to ask
for "a property named 'phone'".

E.g., a trivial example...:

def add_property(cls, name):
    def get(self):
        return getattr(self, '_'+name)
    def set(self, value):
        setattr(self, '_'+name, value)
    setattr(cls, name, property(get, set))

this shows how to add a property that's a pair
of trivial accessors which just map get and set
to an underlying data attribute which has the
same name plus a leading underscore; of course,
in your case the get and set will be way more
elaborate, but I hope this might have all the
elements you might have been missing -- setattr,
getattr, closures, the property descriptor type
and how it's used...


Alex

        




More information about the Python-list mailing list