How to Call a Function by String Name in Python [8 Methods]

In this Python tutorial, we will discuss “How to call a function by string name in Python,” we will see 8 different approaches with some demonstrative examples.

To call a function by its string name in Python, we will use some built-in methods of Python like getattr(), globals(), eval(), exec(), etc., and some different approaches and techniques to call a Python function with a string.

Here is the list of all 8 different approaches to calling Python functions by string name

  1. using getattr()
  2. using globals()
  3. using a dictionary
  4. using eval()
  5. using exec()
  6. locals()
  7. call a class method by string name
  8. using importlib module

Call a function by string name in Python using getattr() function

The getattr() function in Python retrieves the value of a specified attribute from an object, which is useful to make your code more readable, especially when dealing with dynamic attribute access to call a function by string name.

Code

import math
function_name = 'sqrt'
calculate_square_root = getattr(math, function_name)
result = calculate_square_root(25)
print(result)

In this code, getattr(math, function_name) retrieves the’ sqrt’ attribute from the math module in Python. This attribute happens to be a function that calculates the square root in Python.

calculate_square_root = getattr(math, function_name)

By dynamically accessing this attribute using getattr() function in Python, you can programmatically select which function to call based on a variable (function_name in this case).

READ:  How to Find the Smallest Number in a Python List [8 Ways]

Output

5.0

Attached are snapshots illustrating the Python code and its corresponding output in Visual Studio

How to Call a Function by String Name in Python

Call Python function by string name using globals()

You can call a function by its name, provided as a string, using the globals() function in Python. This function returns a dictionary representing the global symbol table, which includes all functions defined at the global level.

Here is an instance to call a function by string name in Python using the globals() function:

Code

def calculations(a, b):
    print(f'Addition : {a+b}')
    print(f'Subtraction : {a-b}')
    print(f'Multiplication : {a*b}')
    print(f'Division : {a/b}')
    
function_name = globals()['calculations']
function_name(30,15)

In this code, function_name is assigned the value retrieved from the global symbol table using globals()[‘calculations’], the function object of calculations.

Output

Addition : 45
Subtraction : 15
Multiplication : 450
Division : 2.0

Here’s a combined view of the Python script and its output within Visual Studio

Calling a function of a module by using its name in Python

Calling a function by string name in Python by using a dictionary

To call a function by string name in Python, you can use a dictionary that maps function names to their corresponding function objects.

Here is an example to call a function by string name in Python using a dictionary:

Code

def calculate_tax(income, tax_rate):
    return income * tax_rate

functions_dict = {
    'calculate_tax': calculate_tax,
}
function_name = 'calculate_tax'
if function_name in functions_dict:
    print(functions_dict[function_name](50000, 0.2))

A dictionary named functions_dict is created, where the key ‘calculate_tax’ corresponds to the function calculate_tax. Next, the variable function_name is assigned the string ‘calculate_tax’.

if function_name in functions_dict:
    print(functions_dict[function_name](50000, 0.2))

If statement checks if function_name exists in functions_dict, and if so, it calls the function using functions_dict[function_name] with its arguments.

Output:

10000.0

Displayed below is the Python code alongside its output, captured in Visual Studio.

Call a Function by a String name in Python

How to use strings to call functions using eval() in Python

We can use the eval() function in Python to execute a string as Python code. This includes calling functions dynamically based on string names.

READ:  Sum of Squares of Digits of a number in Python

Here is how we can call a function by string name in Python using eval():

Code

def customer_service_greeting(name):
    return f'Hello {name}, thank you for contacting our customer service. How can I assist you today?'

function_name = 'customer_service_greeting'
func = eval(function_name)
print(func('Peter Parker'))

Output

Hello Peter Parker, thank you for contacting our customer service. How can I assist you today?

A screenshot of the Python code and its output in Visual Studio is presented.

How To Call a Python Function With A String

Call a function from a string name in Python using exec()

You can call a function from a string name using the exec() function and dynamic variable assignment in Python. This approach allows for dynamic execution of code defined by strings.

Here is an example:

Code

def calculate_sales_tax(amount):
    tax_rate = 0.08  
    return amount * tax_rate

function_name = 'calculate_sales_tax'
exec(f'my_func={function_name}')
my_func = globals()['my_func']
print(my_func(100)) 

The exec() function is used to dynamically execute the string f’my_func={function_name}’, effectively creating a variable my_func that holds the function object of calculate_sales_tax in Python.

exec(f'my_func={function_name}')

my_func is retrieved from the global symbol table using globals()[‘my_func’], and called with the argument in Python.

Output

8.0

Attached is a merged image displaying both the Python code and its output in Visual Studio

How to use strings to call methods in Python

How to use strings to call methods in Python using locals().py

The locals() is the built-in method in Python, which we can call a method from string names.

We called locals(), effectively accessing the method object of calculate_shipping_cost from the local symbol table.

Code

def calculate_shipping_cost(weight, distance):
    rate_per_mile = 0.5 
    return weight * distance * rate_per_mile

print(
locals()['calculate_shipping_cost'](20, 100)
)

Output

1000.0

Here is a consolidated view of the Python code and its output within Visual Studio.

Convert String to a function call in Python

Call a class method by string name in Python

We can also call a class method by string name in Python using getattr(). We’ve explained the getattr() method in the first example.

READ:  How to Split the Last Element of a String in Python

Code

class Customer():
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def get_full_name(self):
        return self.first_name + ' ' + self.last_name

custormer_object = globals()['Customer']
customer1 = custormer_object('John', 'Doe')
func = getattr(customer1, 'get_full_name')
print(func()) 

Output

John Doe

Below is a combined screenshot of the Python code and its output in Visual Studio.

How to Call a Function From String Name in Python

Calling a function of a module by using the importlib module in Python

In Python, you can call a function of a module by using the importlib module. This module provides a way to dynamically import other modules or specific attributes (such as classes or functions) at runtime.

Code:

# Emp_Details.py 

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

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

Code for main.py File

# main.py 

import importlib
module = importlib.import_module('Emp_Details')
cls = getattr(module, 'Employee')
emp1 = cls('John', 'Doe')
func = getattr(emp1, 'get_name')
print(func())

This code contains two files: Emp_Details.py, which defines a class Employee, and main.py, where the class Employee from Emp_Details.py is imported.

import importlib
module = importlib.import_module('Emp_Details')
cls = getattr(module, 'Employee')

And getattr(module, ‘Employee’) retrieves the class object Employee from the imported module. This showcases how to dynamically call a function of a module using the importlib module in Python.

Output

John Doe

Below is a dual-view screenshot exhibiting the Python code and its output in Visual Studio.

How to call a function of a module by using its name in Python
How to call a function by its name as a string in Python

Conclusion

Here, we explored various methods to call a function by string name in Python, showcasing eight approaches and techniques. We discussed how to use built-in functions like getattr(), globals(), eval(), exec(), and locals(), as well as utilizing dictionaries, class methods, and the importlib module to call functions by string name.

Each method provides a different way to dynamically call functions based on string names, offering flexibility and versatility in Python programming.

You may also like to read: