Python - How To Calling a Function From String Name in Python

ID : 117

viewed : 125

Tags : PythonPython FunctionPython String

vote vote


This tutorial will introduce how to call a function using its name in string format in Python.

The use-case for this problem is to assign a function from a module or a class into a variable for whatever use it may have.

Use getattr() to Assign a Function Into a Variable in Python

The function getattr() returns a value of an attribute from an object or module. This function has two required arguments, the first argument is the name of the object or module, and the second is a string value that contains the name of the attribute.

The attribute in question may be in the form of a variable, a function, or a subclass.

Let’s say we have a class named User with the given attributes:

# Filename: class User():   name = 'John'   age = 33   def doSomething():     print(name + ' did something.') 

Now, we want to store the attribute function doSomething() into a method and call it. To do this, we’ll use the getattr() function.

from user import User as user  doSomething = getattr(user, 'doSomething')  doSomething(user) 


John did something. 

Now, the function user.doSomething() is wrapped within the variable doSomething. This way, the object user doesn’t have to be specified to call the function.

Use locals() and globals() to Call a Function From a String in Python

Another way to call a function from a string is by using the built-in functions and . These two functions return a that represents the current symbol table of the given source code.

The difference between the two functions is the namespace. As the names indicate, locals() returns a dictionary including local variables and globals() returns a dictionary including local variables. Function names are also returned in the format of the string.

Let’s put these methods into an example. Declare 2 random functions and call it using both built-in functions.

def myFunc():     print('This is a function.')  def myFunc2():     print('This is another function.')  locals()['myFunc']() globals()['myFunc2']() 


This is a function. This is another function. 

In summary, to call a function from a string, the functions getattr(), locals(), and globals() are used. getattr() will require you to know what object or module the function is located in, while locals() and globals() will locate the function within its own scope.

  • Related HOW TO?