Question
How can I call a function from a Python module when I only have the function name as a string?
For example:
import foo
func_name = "bar"
call(foo, func_name) # should call foo.bar()
What is the correct Python way to dynamically call foo.bar() using the string stored in func_name?
Short Answer
By the end of this page, you will understand how Python can look up functions dynamically by name, how to use getattr() to access a function from a module or object, how to call it safely, and when a dictionary-based dispatch pattern is a better choice.
Concept
In Python, functions inside a module are attributes of that module. That means if a module contains a function like bar, Python stores it similarly to how it stores variables and constants on that module.
When you write:
import foo
foo.bar()
Python is accessing the bar attribute from the foo module and then calling it.
If the function name is stored as a string, you cannot write foo.func_name() because that looks for a function literally named func_name. Instead, you need a way to ask Python:
- "Get the attribute whose name is this string"
- Then call it if it is a function
The built-in function getattr() is the standard tool for this.
function = getattr(foo, "bar")
function()
This matters because dynamic lookup is common in real programs:
- command handlers
- plugin systems
- configuration-based behavior
- API routing
- event processing
However, dynamic function calls should be used carefully. If the string comes from a user or external input, blindly calling whatever name is provided can be unsafe or lead to hard-to-debug code. In many real projects, developers use a controlled dispatch table instead of unrestricted dynamic lookup.
Mental Model
Think of a Python module like a toolbox with labeled compartments.
- The module is the toolbox
- Each function is a tool inside it
- The function name is the label on the compartment
getattr(module, name)means: "Open the compartment with this label"
If the label exists, you get the tool. If not, Python raises an error.
Then calling the function is like taking the tool out and using it.
So this:
foo.bar()
is the direct version, while this:
name = "bar"
getattr(foo, name)()
is the version where you first look up the label dynamically.
Syntax and Examples
The core syntax is:
getattr(object_or_module, attribute_name)
To call a function by name from a module:
import foo
func_name = "bar"
func = getattr(foo, func_name)
func()
You can also do it in one line:
getattr(foo, func_name)()
Example 1: Simple dynamic function call
Suppose foo.py contains:
# foo.py
def bar():
print("Hello from bar")
Then another file can do:
import foo
func_name = "bar"
getattr(foo, func_name)()
Output:
Hello from bar
Example 2: Calling a function with arguments
Step by Step Execution
Consider this code:
# foo.py
def add(a, b):
return a + b
import foo
func_name = "add"
func = getattr(foo, func_name)
result = func(2, 3)
print(result)
Here is what happens step by step:
-
import foo- Python loads the
foomodule. - The function
addbecomes available asfoo.add.
- Python loads the
-
func_name = "add"- A string is stored in
func_name. - This is only text, not a function yet.
- A string is stored in
-
func = getattr(foo, func_name)- Python reads the value of
func_name, which is"add".
- Python reads the value of
Real World Use Cases
Dynamic function lookup is useful when the function to run is not known until runtime.
Command-line tools
A command name can map to a function:
command = "build"
getattr(commands_module, command)()
Plugin systems
A config file may specify which processor to run:
processor_name = config["processor"]
processor = getattr(processors, processor_name)
processor(data)
Event handlers
Different event names can trigger different functions:
event_name = "on_login"
handler = getattr(handlers, event_name)
handler(user)
Data processing scripts
A script may apply a transformation chosen by name:
transform_name = "normalize"
transform = getattr(transforms, transform_name)
clean_data = transform(raw_data)
Testing utilities
Test frameworks and helper scripts sometimes discover functions dynamically by naming rules.
Real Codebase Usage
In real projects, developers often use dynamic lookup in controlled ways rather than calling any arbitrary string.
1. Guard clauses before calling
func = getattr(foo, func_name, None)
if func is None:
raise ValueError(f"Unknown function: {func_name}")
return func()
This avoids crashing with an unclear error.
2. Check that the attribute is callable
Not every attribute on a module is a function.
value = getattr(foo, func_name, None)
if value is None:
raise ValueError("Not found")
if not callable(value):
raise TypeError(f"{func_name} exists but is not callable")
value()
3. Use a dispatch table for safety
This is often better when only a few functions are allowed.
import foo
DISPATCH = {
"bar": foo.bar,
"baz": foo.baz,
}
func = DISPATCH.get(func_name)
func :
ValueError()
func()
Common Mistakes
Mistake 1: Using dot notation with the variable name
Broken code:
import foo
func_name = "bar"
foo.func_name()
Why it is wrong:
- Python looks for an attribute literally named
func_name - It does not use the string value stored in the variable
Correct version:
getattr(foo, func_name)()
Mistake 2: Forgetting to call the function
Broken code:
func = getattr(foo, "bar")
print(func)
This prints the function object instead of running it.
Correct version:
func = getattr(foo, "bar")
func()
Mistake 3: Not handling missing names
Broken code:
func = getattr(foo, "does_not_exist")
func()
This raises AttributeError.
Comparisons
| Approach | How it works | Best for | Pros | Cons |
|---|---|---|---|---|
| Direct call | foo.bar() | Known function names | Simple and clear | Not dynamic |
getattr() | getattr(foo, "bar")() | Dynamic lookup on modules or objects | Flexible, built-in | Can be unsafe if unrestricted |
| Dispatch dictionary | handlers["bar"]() | Controlled set of actions | Safe, explicit, readable | Requires manual mapping |
getattr() vs dispatch dictionary
Cheat Sheet
Core pattern
func = getattr(module, "function_name")
func()
One-line call
getattr(module, name)()
With arguments
getattr(module, name)(arg1, arg2)
Safe lookup with default
func = getattr(module, name, None)
if func is not None:
func()
Check callability
value = getattr(module, name, None)
if callable(value):
value()
Safer controlled alternative
DISPATCH = {
"bar": foo.bar,
"baz": foo.baz,
}
func = DISPATCH.get(name)
if func:
func()
Rules to remember
FAQ
How do I call a function by string name in Python?
Use getattr():
func = getattr(foo, "bar")
func()
Can I call foo.func_name() if func_name = "bar"?
No. That looks for an attribute literally named func_name. To use the string value, use getattr(foo, func_name).
What happens if the function name does not exist?
getattr() raises AttributeError unless you provide a default value:
getattr(foo, func_name, None)
Can getattr() return something other than a function?
Yes. It returns any attribute with that name, such as strings, numbers, classes, or variables. Use callable() if you need to verify that it can be called.
Is getattr() safe to use with user input?
Not by itself. If the name comes from a user, it is better to validate it or use a dispatch dictionary with only allowed functions.
Mini Project
Description
Build a small command runner that chooses which function to execute based on a string command. This demonstrates dynamic function lookup in a practical way and also shows how to validate commands before calling them.
Goal
Create a Python program that runs functions from a module based on a command name string and handles invalid names safely.
Requirements
- Create a module with at least three functions.
- Store the function name in a string variable before calling it.
- Use
getattr()to look up and run the function. - Prevent crashes when the function name does not exist.
- Verify that the found attribute is callable before executing it.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.