Skip to main content

How to Call Functions by String Name in Python

Sometimes you need to call a function when its name is stored in a string.

This guide explores various techniques for calling a function using a string name in Python, emphasizing safe and recommended practices. We'll cover techniques using getattr(), globals(), dictionaries, and also discuss the use and potential risks associated with eval() and exec().

Calling Functions using getattr()

The getattr() function allows you to dynamically access attributes of an object, including functions. To call a function using a string name with getattr():

import example_module

func = getattr(example_module, 'example_function')
print(func('ab', 'cd')) # Output: abcd

Calling Functions from a Different Module

The above example assumes you have a module named example_module in the same directory with a function named example_function.

def example_function(a, b):
return a + b
  • The getattr() function retrieves the function from the module, using the name as a string.
  • The function obtained using getattr() can be called like any other function.

Calling Class Methods using getattr()

You can also use getattr() to call a method on an object:

class Employee():
def __init__(self, first, last):
self.first = first
self.last = last

def get_name(self):
return self.first + ' ' + self.last

cls = globals()['Employee']
emp1 = cls('Tutorial', 'Reference')
func = getattr(emp1, 'get_name')
print(func()) # Output: Tutorial Reference
  • In this case globals() is used to obtain the class by name using string.
  • getattr() then gets the get_name method of the emp1 object.

Importing and Calling Class Methods from Another Module

You can use getattr to call class methods in other modules:

import example_module

cls = getattr(example_module, 'Employee')
emp1 = cls('Tutorial', 'Reference')
func = getattr(emp1, 'get_name')
print(func()) # Output: Tutorial Reference
  • The getattr() is used to get the Employee class from example_module.
  • Then getattr() is used to access the class instance emp1 method get_name.

If you need to import a module dynamically, you can use the importlib.import_module() method:

import importlib
module = importlib.import_module('example_module')
cls = getattr(module, 'Employee')
emp1 = cls('Tutorial', 'Reference')
func = getattr(emp1, 'get_name')
print(func()) # Output: Tutorial Reference

Calling Functions using globals()

If the function you want to call is in the current module, use globals():

def do_math(a, b):
return a + b
func = globals()['do_math']
print(func(10, 5)) # Output: 15
  • The globals() function returns a dictionary of the current module's global namespace.
  • The function is accessed by using its name as a key to the dictionary.
  • You can then call the obtained function like a normal function, passing arguments using parentheses.

Calling Functions using a Dictionary

For a more controlled approach, use a dictionary to map names to functions:

def do_math(a, b):
return a + b

functions_dict = {
'do_math': do_math,
}
function_name = 'do_math'

if function_name in functions_dict:
print(functions_dict[function_name](10, 5)) # Output: 15
  • The dictionary functions_dict holds the function names and the functions themselves.
  • You can then look up a specific function using it's name.
  • Always check if the function name exists in the dictionary to avoid exceptions.

Calling Functions using locals()

If a function is defined in the current scope you can use locals() to get the function by a string name, this works very similar to globals().

def example_function(a, b):
return a + b

print(
locals()['example_function'](50, 55)
) # Output: 105
  • The locals() dictionary returns a dictionary with the local scope variables.
  • You can get the function by using its string name as a key.

globals() vs locals()

globals() will return the module namespace, while locals() will return the namespace from the current scope. This is demonstrated in the following code:

def example_function():
return 'GLOBAL example function'

def call_function_by_string_name():
def example_function():
return 'LOCAL example function'
print(globals()['example_function']())
print('-' * 30)
print(locals()['example_function']())

call_function_by_string_name()

Output:

GLOBAL example function
------------------------------
LOCAL example function

Dangers of Using eval()

The eval() function can also be used to call a function by its string name. However, be very careful as this is a very insecure way of calling code and should not be used with untrusted input:

def greet(name):
return f'hello {name}'

function_name = 'greet'
func = eval(function_name)
print(func('Tutorial Reference')) # Output: hello Tutorial Reference
note

eval() executes a string as Python code. It poses a high security risk and should only be used with trusted input. Do not use eval() with user-provided strings.

Dangers of Using exec()

The exec() function can be used to dynamically execute Python code, including the execution of functions. However, it is an extremely insecure way to accomplish this and should never be used with untrusted input:

def greet(name):
return f'hello {name}'
function_name = 'greet'
exec(f'my_func={function_name}')
print(my_func('Tutorial Reference')) # Output: hello Tutorial Reference
note

exec() has very significant security risks if used with untrusted input, and can introduce security vulnerabilities into your code. For these reasons, you should use a dictionary instead.