How to Call a Function by String in Python?

In Python, functions are typically called using their direct names. However, there are scenarios where you might need to call a function dynamically using a string representation of its name. In this tutorial, I will explain how to call a function by string in Python using different methods with examples.

To call a function by its string name in Python, you can use the getattr() function. This built-in function retrieves the attribute of an object by name. For example, if you have a class MyClass with a method my_function, you can call it dynamically by using method = getattr(obj, 'my_function') followed by method(). This approach is safe and commonly used for dynamic function calls.

Call a Function by String in Python

There can be many scenarios in which you need to call a function by its string name in Python, like a dynamic function call, When the function to be executed is not known until runtime.

Now, let me show you different methods of calling a function by string in Python with some real examples.

1. Using getattr()

The getattr() function is a built-in function in Python that returns the value of the named attribute of an object. If the named attribute does not exist, it returns the default value.

Syntax:

Here is the syntax.

getattr(object, name[, default])

Example:

Here is an example.

class MyClass:
    def my_function(self):
        print("Function called")

obj = MyClass()
function_name = "my_function"
method = getattr(obj, function_name)
method()  # Output: Function called

Here is the output in the screenshot below:

Call a Function by String in Python

Let me show you another real example of how to use the getattr() function to call a function by a string in Python.

Example:

class USAWeather:
    def get_weather(self):
        print("Fetching weather data for the USA...")

weather_obj = USAWeather()
function_name = "get_weather"
method = getattr(weather_obj, function_name)
method()  # Output: Fetching weather data for the USA...

In this example, the USAWeather class has a method get_weather that fetches weather data. Using getattr(), we dynamically call this method by its string name, which is useful for applications like weather apps that need to call different functions based on user input.

Check out How to Call a Function in Python?

2. Using globals() and locals()

The globals() and locals() functions in Python return the global and local symbol tables, respectively. These can be used to access functions defined in the global or local scope.

Let me show you an example.

Example:

def my_function():
    print("Function called")

function_name = "my_function"
globals()[function_name]()  # Output: Function called

Here is another real example of calling a function by string in Python.

Example:

def get_usa_population():
    print("Fetching population data for the USA...")

function_name = "get_usa_population"
globals()[function_name]()  # Output: Fetching population data for the USA...

Here, the function get_usa_population prints the population data for the USA. By storing the function name as a string and using globals(), we dynamically call the function. This method is often used in data analysis scripts that need to call different functions based on configuration files.

You can see the exact output in the screenshot below:

python call function by string

Check out Python Function Examples with Parameters

3. Using eval()

The eval() function parses the expression passed to it and executes Python expression (code) within it. This method should be used cautiously due to security concerns.

Here is an example to understand this.

Example:

Here is an example.

def my_function():
    print("Function called")

function_name = "my_function"
eval(function_name + '()')  # Output: Function called

Here is another real-time example.

Example:

def get_usa_gdp():
    print("Fetching GDP data for the USA...")

function_name = "get_usa_gdp"
eval(function_name + '()')  # Output: Fetching GDP data for the USA...

In this example, the function get_usa_gdp prints GDP data for the USA. Using eval(), we dynamically call the function by constructing the function call as a string. While powerful, this method should be used cautiously due to security concerns, especially in financial applications.

Here is the output in the screenshot below:

How to Call a Function by String in Python

Check out Return Multiple Values from a Function in Python

4. Using __dict__

You can use the __dict__ attribute of a class or module to access its members, including functions, by name.

Let me show you an example.

Example:

class MyClass:
    def my_function(self):
        print("Function called")

obj = MyClass()
function_name = "my_function"
obj.__dict__[function_name]()  # Output: Function called

Here is another example.

Example:

class USACities:
    def get_city_data(self):
        print("Fetching data for major cities in the USA...")

cities_obj = USACities()
function_name = "get_city_data"
cities_obj.__dict__[function_name]()  # Output: Fetching data for major cities in the USA...

The USACities class has a method get_city_data that fetches data for major cities in the USA. By accessing the __dict__ attribute, we dynamically call the method using its string name. This technique is useful for applications that manage large datasets, such as city information databases.

Conclusion

In this tutorial, I have explained how to call a function by its string name in Python using the below methods:

  1. Using getattr()
  2. Using globals() and locals()
  3. Using eval()
  4. Using dict

I have also explained one real example for each method. Is this tutorial helpful to you? Leave a comment below.

You may also like:

Leave a Comment