how to dynamically create class methods ?

j vickroy jim.vickroy at
Tue Mar 25 21:17:16 CET 2008

Arnaud Delobelle wrote:
> On Mar 25, 6:13 pm, j vickroy <jim.vick... at> wrote:
>> Hello,
>> Here is some pseudo-code that hopefully illustrates what I want to do:
>> records = list(...)
>> for record in records:
>>     new_fcn = define_a function_for(record)
>>     instance = my_new_class_instance()
>>     setattr(instance, 'myfcn', new_fcn)
>>     instance.execute() # instance.execute() calls instance.myfcn(*args)
>> I have looked at some of the functions in the *new* module and
>> new.code(...), new.function(...), and new.instancemethod(...) appear to
>> do what I want, but I do not know how to use new.code() and
>> new.function() -- specifically what its *global* parameter should be.
> The best way to understand how new.function and new.code work is to
> look at the Python source.  (Objects/funcobject.c and Objects/
> codeobject.c, actual objects are defined in and Include/funcobject.h
> Include/code.h).
> However, to create a function dynamically in Python it is often no
> more trouble than a def statement:
> Funnily enough I can't think of a nice example ATM so here is a bad
> one: say you want to create a function that checks the spelling of a
> word, regardless of case.  You could a function that returns on-the-
> fly created functions that check the spelling of a word like this:
> def get_spellchecker(word):
>     word = word.upper()
>     def check_spelling(candidate):
>         return candidate.upper() == word
>     return scheck_spelling
> Then
>>>> check_hypo = get_spellchecker('hypopothamus')
>>>> check_hypo('Hypopothamus')
> True
>>>> check_hypo('Big scary mammal')
> False
> (Warning: this is all untested).
> --
> Arnaud

Thanks for your reply, Arnaud.

As per your suggestion, I tried looking at include/code.h and 
include/funcobject.h (my MS Windows distribution does not appear to 
contain .c files).  However, since I'm not a C programmer, I did not 
find the .h files all that helpful.

What I failed to make clear in my original posting is that the functions 
must be created dynamically using information in a *record* as the code 
iterates over all *records*.  So, I can not pre-define the functions and 
then simply select the desired one at run-time.

-- jv

More information about the Python-list mailing list