JChao
JChao

Reputation: 91

Retrieving a method by using string of method's name? Python

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?

Upvotes: 1

Views: 374

Answers (5)

John Machin
John Machin

Reputation: 82924

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.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599530

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

Upvotes: 1

Oli
Oli

Reputation: 239810

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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

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

getattr(someobj, methodDict[someval])

Upvotes: 6

g.d.d.c
g.d.d.c

Reputation: 47978

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

Upvotes: 3

Related Questions