how to make a code object a function

Peter Otten __peter__ at web.de
Sun Jan 4 09:11:05 EST 2004


Diez B. Roggisch wrote:

> Hi,
> 
> I've got code objects that are created from strings at runtime that look
> like this:
> 
> def p_op1(_, args):
>     _.add_dependency('p_op1')
> 
> As you migth guess, p_op1 is supposed to become an instance method. Now
> how do I make this code object a function-object that can be set into the
> instances __dict__ to make it a callable method?

Too lazy to type self?

>>> import types
>>> class T(object):
...     def add_dependency(self, name):
...             print "adding dependency", name
...
>>> t = T()
>>> def p_op1(_, args):
...     _.add_dependency("p_op1")
...
>>> t.p_op1 = types.MethodType(p_op1, t)
>>> t.p_op1(1)
adding dependency p_op1
>>>

By the way, types.MethodType and new.instancemethod seem to be equivalent.

Peter



More information about the Python-list mailing list