How to Call a Function by String Name in Python

To call a function by string name in Python, look the name up and then call what you get back. Use getattr(module, name) for functions in a module or methods on an object, and globals()[name] for functions defined in the same file:

import math

func = getattr(math, "sqrt")
print(func(16))                 # 4.0

My test machine for these snippets ran Python 3.12.5 on Windows, and each output block is the exact text it printed.

In this tutorial, we’ll cover globals(), getattr(), importlib, dispatch dictionaries, eval() risks and missing names.

How do you call a function by its string name with globals()?

globals() returns the module’s namespace as a dictionary, so a function name is just a key. Grab the function object with the string, then add parentheses to call it:

def sales_report(month):
    return f"Sales report for {month} 2026: $48,250.00"

def refund_report(month):
    return f"Refund report for {month} 2026: $1,320.75"

name = "sales_report"            # the name arrives as a string
func = globals()[name]           # look it up in the module namespace
print(func.__name__, callable(func))
print(func("March"))
print(globals()["refund_report"]("March"))

def run_local():
    def inner_total():
        return 99.50
    return locals()["inner_total"]()

print(run_local())

Output:

sales_report True
Sales report for March 2026: $48,250.00
Refund report for March 2026: $1,320.75
99.5
Command Prompt output of Python calling functions by string name through globals() and locals()
Both report functions are found from their string names, and the nested helper is reached through locals().

locals() does the same job for names inside the current function. If calling with parentheses is still new to you, read how to call a function in Python first.

Call a module function or class method with getattr()

getattr(obj, name) works on modules, classes and instances. It’s among the Python built-in functions, and its third argument is a default that saves you from an AttributeError:

import math

class Invoice:
    def __init__(self, amount):
        self.amount = amount

    def with_tax(self, rate=0.0825):
        return round(self.amount * (1 + rate), 2)

    def with_discount(self, pct=10):
        return round(self.amount * (1 - pct / 100), 2)

print(getattr(math, "sqrt")(144))

inv = Invoice(250.00)
for action in ("with_tax", "with_discount"):
    method = getattr(inv, action)          # bound method, self is filled in
    print(action, "->", method())

print(getattr(Invoice, "with_tax")(inv, 0.06))
print("with_coupon:", getattr(inv, "with_coupon", None))

Output:

12.0
with_tax -> 270.62
with_discount -> 225.0
265.0
with_coupon: None
Command Prompt output of Python getattr() calling math functions and Invoice methods by string name
The math function and both Invoice methods run from their names, and the missing with_coupon falls back to None.

An instance gives you a bound method with self filled in; on the class, I pass the instance myself.

The same lookup works for data attributes too; dynamic attributes with setattr() and getattr() covers that side.

Load a function from a module name string with importlib

When the module name is a string too, like "reports.monthly_total", split off the last part, import the module with importlib.import_module(), then call getattr():

import importlib

def load(path):
    module_name, func_name = path.rsplit(".", 1)
    module = importlib.import_module(module_name)
    return getattr(module, func_name)

monthly = load("reports.monthly_total")
print(monthly([1200.00, 845.50, 310.25]))

Output:

Monthly total: $2,355.75

For the plain, static version, see calling a function from another file in Python.

Use a dispatch dictionary for user input

When the string comes from a user, a dictionary of allowed names is the safest choice. Only listed functions can run:

def add_item(name, price):
    return f"Added {name} at ${price:.2f}"

def remove_item(name):
    return f"Removed {name}"

def show_total():
    return "Cart total: $64.48"

COMMANDS = {"add": add_item, "remove": remove_item, "total": show_total}

def run(command, *args):
    func = COMMANDS.get(command)
    if func is None:
        return f"Unknown command {command!r}. Try: {', '.join(COMMANDS)}"
    return func(*args)

print(run("add", "Coffee beans", 14.99))
print(run("remove", "Mug"))
print(run("total"))
print(run("delete_all"))

Output:

Added Coffee beans at $14.99
Removed Mug
Cart total: $64.48
Unknown command 'delete_all'. Try: add, remove, total
Command Prompt output of a Python dispatch dictionary turning command strings into function calls
The add, remove and total commands each run their function, while the unknown command lists the valid choices.

*args passes along however many values each command needs. Default values help here too; see Python functions with optional arguments.

Why is eval() risky for calling a function by name?

eval() can call a function from a string, but it runs any expression you give it. exec() goes further and can define a brand-new function from source text:

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

name = "add"
print(eval(f"{name}(3, 5)"))

user_text = "__import__('platform').system()"
print("eval also ran:", eval(user_text))     # any expression runs, not just names

source = """
def shipping(weight_lb):
    return 5.99 if weight_lb <= 2 else round(5.99 + (weight_lb - 2) * 1.25, 2)
"""
namespace = {}
exec(source, namespace)                      # defines shipping() inside namespace
shipping = namespace["shipping"]
print(shipping(1.5), shipping(6))

Output:

8
eval also ran: Windows
5.99 10.99

The second line shows why: a fake name imported a module and ran it. Don’t pass user input to either one. Both build on the Python compile() function.

If users type formulas, parse them with the ast module and allow only numbers, known names and math operators:

import ast
import operator as op

OPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv}

def safe_calc(expr, **values):
    def walk(node):
        if isinstance(node, ast.Expression):
            return walk(node.body)
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.Name) and node.id in values:
            return values[node.id]
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](walk(node.left), walk(node.right))
        raise ValueError(f"{type(node).__name__} is not allowed")
    return walk(ast.parse(expr, mode="eval"))

print(round(safe_calc("price * qty - discount", price=19.99, qty=3, discount=5), 2))
try:
    safe_calc("__import__('platform').system()")
except ValueError as err:
    print("Blocked:", err)

Output:

54.97
Blocked: Call is not allowed
Command Prompt output of a safe Python formula evaluator built with the ast module
The price formula returns 54.97, and the attempted import is blocked because a function call isn’t on the allowed list.

I use this pattern for pricing rules stored in a spreadsheet.

Handle missing or invalid function names

A bad name raises KeyError from globals()[name] or AttributeError from getattr(). Use .get() and check the result with the callable() function so a variable name can’t sneak through:

def tax(amount):
    return round(amount * 0.0825, 2)

def call_by_name(name, *args):
    func = globals().get(name)
    if not callable(func):
        raise ValueError(f"{name!r} is not a function I can call")
    return func(*args)

print(call_by_name("tax", 120.00))
for bad in ("taxes", "__name__"):
    try:
        call_by_name(bad, 1)
    except ValueError as err:
        print("Error:", err)

Output:

9.9
Error: 'taxes' is not a function I can call
Error: '__name__' is not a function I can call

__name__ exists but it’s a string, so callable() rejects it. Each target here is an ordinary def; see how to define a function in Python.

Once a lookup works, these pages help you inspect and reuse what it returns:

Frequently asked questions

How do I call a function from a string in Python?

Look it up with getattr(module, name) or globals()[name], then call it.

Is it the same as converting a string to a function?

Usually. Look up existing functions by name; for strings holding code, ast parsing beats exec().

Is eval() safe for calling functions by name?

No. eval() runs any expression, so a crafted string can import modules or delete files.

What’s the safest way to map user input to functions?

A dispatch dictionary of allowed names, with .get() for unknown commands.

How do I call a class method by its string name?

Use getattr(instance, "method_name")(). The bound method already has self.

Where is getattr() documented?

See getattr() in the official Python built-in functions reference.