Dynamically Generate Methods

Duncan Booth duncan.booth at invalid.invalid
Fri Nov 18 12:52:49 EST 2011


GZ <zyzhu2000 at gmail.com> wrote:

> 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?
> 

Use operator.itemgetter:

>>> key_attrs = ['A', 'B']
>>> import operator
>>> get_key = operator.itemgetter(*key_attrs)
>>> d = {'A': 42, 'B': 63, 'C': 99}
>>> get_key(d)
(42, 63)

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list