1

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?

5 Answers 5

6

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

getattr(someobj, methodDict[someval]) 
Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

1

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]() 

Comments

0

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.

1 Comment

Thanks, this did the trick for what was needed for now. Might need getattr later, but the globals() got me going :)
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.