dynimac code with lambda function creation

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Mar 27 18:02:57 CET 2008


Justin Delegard a écrit :
> So I am trying to pass an object's method call

I assume you mean "to pass an object's method", since I don't get what 
passing "an object's method call" could mean.

> to a function that 
> requires a function pointer. 

s/pointer/object/

There's nothing like a pointer in Python, and Python's functions are 
plain objects (instances of class 'function'). FWIW and WWAI, Python's 
methods are thin callable wrappers around the function, the class and 
(for bound methods) the instance.

> 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.

"easy" ???

Here's the easy way to pass a method to a function:

def func(method):
   return method(42)

class MyClass(object):
   def __init__(self, name):
     self.name = name

   def foo(self, whatever):
      return "I'm %s and whatever is %s" % (self.name, str(whatever))


obj = MyClass('boo')
print func(obj.foo)


> Here is the function I'm using:
> 
> def objectMethodCallerFunctionCreator(testerObj, method):
>    exec("y=lambda x: testerObj."+method+"(x)")
>    return y

My my my... Looks like you're in for the Rube Goldberg Award !-)

Whenever you think exec (or eval FWIW) is the solution, odds are there's 
a way better solution.

If what you want is to retrieve a reference to an attribute you only 
know by it's name, getattr() is your friend. And in Python, methods are 
attributes.

def objectMethodCallerFunctionCreator(testerObj, method):
      y = lambda x: getattr(testerObj, method)(x)
      return y

But as we've seen above, all this is useless overcomplexification. Just 
pass the method like it was any other attribute, and you're done.

> 
> 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.

This is related to exec as far as I can tell.

>  I have successfully created 
> similar functions, except without using the exec() call. e.g.
> 
> def functionCreator(a, b, c):
>    return lambda d: myFunc(a, b, c, d)
> 
> and it doesn't complain about the variables a, b, or c when being run.  
> 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.   Is there
> some other way to do this that I'm missing? 

print func(getattr(obj, 'foo'))

> I tried passing in 'method' 
> as a function pointer (to the method of the object), but that didn't 
> work either.

What did you try, and what result did you get ? 'does not work' is 
(almost) the most useless description of a problem.




More information about the Python-list mailing list