Dynamically Generate Methods

GZ zyzhu2000 at gmail.com
Fri Nov 18 09:51:12 EST 2011


Hi,

I have a class Record and a list key_attrs that specifies the names of
all attributes that correspond to a primary key.

I can write a function like this to get the primary key:

def get_key(instance_of_record):
   return tuple(instance_of_record.__dict__[k] for k in key_attrs)

However, since key_attrs are determined at the beginning of the
program while get_key() will be called over and over again, I am
wondering if there is a way to dynamically generate a get_ley method
with the key attributes expanded to avoid the list comprehension/
generator.

For example, if key_attrs=['A','B'], I want the generated function to
be equivalent to the following:

def get_key(instance_of_record):
   return (instance_of_record['A'],instance_of_record['B'] )

I realize I can use eval or exec to do this. But is there any other
way to do this?

Thanks,
gz







More information about the Python-list mailing list