dynimac code with lambda function creation

Laszlo Nagy gandalf at shopzeus.com
Thu Mar 27 12:48:25 EDT 2008


Justin Delegard wrote:
> So I am trying to pass an object's method call to a function that 
> requires a function pointer.  I figured an easy way to do it would be to 
> create a lambda function that calls the correct method, but this is 
> proving more difficult than I imagined.
>
> Here is the function I'm using:
>
> def objectMethodCallerFunctionCreator(testerObj, method):
>     exec("y=lambda x: testerObj."+method+"(x)")
>     return y
>   
You are making it too difficult. What about this:

def objectMethodCallerFunctionCreator(testerObj, method):
    return getattr(testerObj,method)

BTW, when you need to return a value (instead of simple code execution) you should use eval() instead of exec().

> Where testerObj is an instance of an object, and method is a string 
> representing the method to call.  The problem is, when I actually run 
> the function created (y in this case), it tells me it can't find the 
> symbol testerObj in the global scope.  
That is true. The 'testerObj' parameter is assigned to the local 
namespace. The local namespace is created when the function is called. 
When you call exec, it creates a new namespace. Thus, testerObj is not 
available inside exec(). But please see above - you do not need exec for 
this. It is unsafe, slow and really not necessary.

> I am assuming this is happening because of the exec() call, but I don't 
> see another way of calling a variable method on an object.  
Generally, you should not use exec, eval and their counterparts to 
access certain attributes of different objects. Same for defining 
functions, classes, create instances etc.

If you still feel that you need to use eval or exec for some reason, 
drop me an email and hopefully I can help avoiding it. :-)

Best,

   Laszlo




More information about the Python-list mailing list