tags:

views:

57

answers:

5

Hi, I'm wondering if it's possible in Python to find a method in a different function by using it's string name.

In one function, I pass in a method:

def register(methods):
    for m in methods:
        messageType = m.__name__
        python_client_socket.send(messageType)


register(Foo)

In a different method that takes in the string that was sent over, I want to be able to associate a number with the method in a dictionary ( i.e. methodDict = {1: Foo, 2:Bar, etc...} )

Is there a way in Python to find the method from the string?

+3  A: 

This accomplishes that type of "if it's defined use it, otherwise let the user know it's not ready yet" feel.

if hasattr(self, method):
  getattr(self, method)()
else:
  print 'No method %s.' % method
g.d.d.c
+5  A: 

If you're certain of the method name (do not use this with arbitrary input):

getattr(someobj, methodDict[someval])
Ignacio Vazquez-Abrams
A: 

globals() will return a dictionary of all local-ish methods and other variables. To launch a known method from a string you could do:

known_method_string = 'foo'
globals()[known_method_string]()

Edit: If you're calling this from a object perspective, getattr(...) is probably better.

Oli
Thanks, this did the trick for what was needed for now. Might need getattr later, but the globals() got me going :)
JChao
+1  A: 

Although other answers are correct that getattr is the way to get a method from a string, if you're prepopulating a dictionary with method names don't forget that methods themselves are first-class objects in Python and can equally well be stored in dictionaries, from where they can be called directly:

methodDict[number]()
Daniel Roseman
+1 because I've had this problem in the past.
Wilduck
A: 
method = getattr(someobj, method_name, None)
if method is None:
    # complain
    pass
else:
    someobj.method(arg0, arg1, ...)

If you are doing something like processing an XML stream, you could bypass the getattr and have a dictionary mapping tags to methods directly.

John Machin