how to dynamically create class methods ?

Arnaud Delobelle arnodel at googlemail.com
Tue Mar 25 15:44:33 EDT 2008


On Mar 25, 6:13 pm, j vickroy <jim.vick... at noaa.gov> 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).

HTH

--
Arnaud




More information about the Python-list mailing list