py. call function by name from current context dynamically

Python dynamically call function by name from current context 2025

Added 'Python' for specificity and included the current year to ensure the results are relevant and up-to-date.

To call a function by its name dynamically in Python, several methods can be employed depending on the context in which you are operating. This guide explores the most common techniques to achieve this, focusing on how to leverage Python's built-in functionality to make function calls using strings representing their names.

Overview

Dynamically invoking a function using its name stored as a string is a powerful feature in Python that allows for greater flexibility in how you structure your code. The most common methods to accomplish this include using the globals() and locals() functions, getattr(), and the eval() function.


Method 1: Using globals()

The globals() function returns a dictionary representing the current global symbol table, which contains all functions defined at the global scope.

Example:

def hello():
    print("Hello, World!")

# Function name as a string
function_name = "hello"

# Call the function dynamically
globals()[function_name]()

In this example, calling globals()[function_name]() dynamically retrieves the hello function and executes it.


Method 2: Using locals()

Similarly, locals() works like globals() but for locally scoped variables. This is especially useful when you want to call a function defined within a specific function or class.

Example:

def call_function():
    def greet():
        print("Greetings!")

    # Function name as a string
    function_name = "greet"

    # Call the function dynamically
    locals()[function_name]()

call_function()

In this case, the greet function is defined within call_function, and we can still invoke it dynamically using locals().


Method 3: Using getattr()

If the function is a method within a class, getattr() is the preferred method. It retrieves an attribute (which can include methods) from an object based on a string name.

Example:

class Greeter:
    def greet(self):
        print("Hello from Greeter!")

# Instantiate the class
greeter = Greeter()

# Method name as a string
method_name = "greet"

# Call the method dynamically
getattr(greeter, method_name)()

With getattr(), you can call methods that belong to an instance, making it a versatile option for object-oriented programming.


Method 4: Using eval()

While eval() enables the execution of dynamically generated Python expressions, it comes with security risks, especially if the input is user-generated. Use eval() cautiously.

Example:

def goodbye():
    print("Goodbye!")

# Function name as a string
function_name = "goodbye"

# Call the function dynamically
eval(function_name + '()')

This method should be avoided in most scenarios unless you are confident about the content being executed, as it can pose a significant security risk.


Conclusion

Dynamically calling functions by name in Python can be accomplished through various methods, each suited for different circumstances. For most use cases, globals() and locals() provide straightforward access to functions in the current namespace, while getattr() is a safe and effective way to handle methods in classes. eval(), though powerful, should generally be reserved for secure environments due to its potential for misuse.

By using these techniques wisely, you can create more flexible and maintainable Python code that responds dynamically to varying inputs and conditions.

People Also Ask

Related Searches

Sources

10
1
python - How to invoke a function on an object dynamically by name?
Stack Overflow

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?

2
Call a function by a String name - Python - GeeksforGeeks
Geeksforgeeks

In this article, we will see how to call a function of a module by using its name (a string) in Python.

3
dynamically patch a Python function's source code at runtime - Eric Ma
Ericmjl

In this blog post, I share how I discovered a powerful Python trick: dynamically changing a function's source code at runtime using the ...

4
Calling Functions by Name in Python - llego.dev
Llego

Learn how to call Python functions dynamically by name using strings with various approaches like globals(), getattr(), eval(), and more.

5
Dynamically calling functions in Python... Safely - Daniel Morell
Danielmorell

As long as we know the name of the function we want to call, we can execute the function and even pass in arguments. This is the idea behind ...

6
How To Call Function By String Name In Python?
Pythonguides

In this tutorial, I will walk you through multiple approaches to dynamically call function by string name in Python with examples.

7
Dynamic dispatch from a string (Python)
Softwareengineering

Dynamically instantiating objects from a class name makes sense in some specialized cases, typically in cases where a constructor function ...

8
Python's exec(): Execute Dynamically Generated Code
Realpython

In this tutorial, you'll learn how to use Python's built-in exec() function to execute code that comes as either a string or a compiled code object.

9
How To Call a Python Function With A String? | by John SS - Medium
Medium

Using getattr() can be handy when you need to call functions dynamically based on user input or other conditions. However, it's important to ...

10
How to call a Python function using its new assigned name - LabEx
Labex

This allows you to dynamically change the name of a function and call it using the new name. Calling Functions Using Getattr(). In addition to using the new ...