How do I use strings to call functions/methods in Python?

Python functions are generally called using their name. However, you can also use strings to call functions dynamically. This is useful when the function name is determined at runtime or stored in variables.

Using locals() and globals()

The locals() function returns a dictionary of local variables, while globals() returns global variables. You can use these dictionaries to call functions by name ?

def demo1():
    print('Demo Function 1')

def demo2():
    print('Demo Function 2')

# Call functions using string names
locals()['demo1']()
globals()['demo2']()
Demo Function 1
Demo Function 2

Using getattr() for Class Methods

The getattr() function retrieves an attribute from an object using a string name. This is particularly useful for calling methods dynamically ?

class Calculator:
    def __init__(self):
        pass
    
    def add(self, a, b):
        return f"Adding: {a} + {b} = {a + b}"
    
    def multiply(self, a, b):
        return f"Multiplying: {a} * {b} = {a * b}"

# Create instance
calc = Calculator()

# Call method using getattr()
method_name = 'add'
func = getattr(calc, method_name)
print(func(5, 3))

# Direct approach
print(getattr(calc, 'multiply')(4, 7))
Adding: 5 + 3 = 8
Multiplying: 4 * 7 = 28

Using eval() (Not Recommended)

While eval() can execute string expressions, it's dangerous and should be avoided for security reasons ?

def greet(name):
    return f"Hello, {name}!"

# Using eval() - AVOID in production code
function_name = "greet"
result = eval(f"{function_name}('Alice')")
print(result)

# Safer alternative using globals()
safe_result = globals()[function_name]('Bob')
print(safe_result)
Hello, Alice!
Hello, Bob!

Comparison of Methods

Method Use Case Safety Performance
globals() Global functions Safe Fast
locals() Local functions Safe Fast
getattr() Object methods Safe Fast
eval() Dynamic expressions Dangerous Slow

Conclusion

Use getattr() for object methods and globals()/locals() for functions. Avoid eval() as it poses security risks and performance issues.

Updated on: 2026-03-26T21:39:24+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements