how to make a code object a function

Diez B. Roggisch deets_noospaam at web.de
Sun Jan 4 10:44:17 EST 2004


Hi,

> Too lazy to type self?

yes. I used an underscore in java as indication for member-variables, so
typing _. appeared natural to me. 
 
>>>> 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.

Interesting - from the docs, I can't see that types.MethodType has a
constructor like this. 

Your example above gave me the idea to simply exec() my code-object, so in
the end I have a new function called p_op1 in my scope - that function I
can get using locals()['p_op1']. I know the name, so that works. 

Just out of curiosity - is there a way to know the name of a code object you
know nothing about except that it will become a function definition? I
guess I could go for some AST-stuff looking for a "def foo" statement, so I
know I will end up having defined foo when exec'ing the code object.

Regards,

Diez B. Roggisch



More information about the Python-list mailing list