Question

Call a Function by Name in a Python Module

pythonobjectreflection

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.

Take Quiz

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

# foo.py

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

func_name = "greet"
func = getattr(foo, func_name)
message = func("Alice")
print(message)

Output:

Hello, Alice!

Example 3: Handling missing functions safely

import foo

func_name = "missing_function"
func = getattr(foo, func_name, None)

if func is None:
    print("Function not found")
else:
    func()

The third argument to getattr() is a default value. If the attribute does not exist, Python returns that default instead of raising an exception.

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:

  1. import foo

    • Python loads the foo module.
    • The function add becomes available as foo.add.
  2. func_name = "add"

    • A string is stored in func_name.
    • This is only text, not a function yet.
  3. func = getattr(foo, func_name)

    • Python reads the value of func_name, which is "add".
    • It looks for an attribute named add on the foo module.
    • It finds the function and stores it in func.
  4. result = func(2, 3)

    • Now func refers to the actual add function.
    • Python calls it with 2 and 3.
    • The function returns 5.
  5. print(result)

    • Python prints 5.

Output:

5

A shorter version is:

print(getattr(foo, "add")(2, 3))

This works, but the multi-line version is usually easier to read and debug.

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.

Take Quiz

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)
if func is None:
    raise ValueError("Invalid function name")

func()

This pattern is easier to validate and maintain.

4. Validation of external input

If the string comes from a request, config file, or user input, developers usually restrict allowed names.

ALLOWED = {"bar", "baz"}

if func_name not in ALLOWED:
    raise ValueError("Function not allowed")

getattr(foo, func_name)()

5. Early returns for clarity

def call_function(module, func_name, *args, **kwargs):
    func = getattr(module, func_name, None)
    if func is None:
        return None
    if not callable(func):
        return None
    return func(*args, **kwargs)

This keeps the control flow simple.

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.

Safer version:

func = getattr(foo, "does_not_exist", None)
if func:
    func()
else:
    print("Function not found")

Mistake 4: Assuming every attribute is callable

Broken code:

# foo.py
version = "1.0"
value = getattr(foo, "version")
value()

This fails because strings are not functions.

Correct version:

value = getattr(foo, "version", None)
if callable(value):
    value()
else:
    print("Attribute is not callable")

Mistake 5: Calling arbitrary user input

Broken idea:

func_name = input("Enter function name: ")
getattr(foo, func_name)()

Why it is risky:

  • users may call unintended attributes
  • errors become harder to control
  • behavior becomes unpredictable

Better approach:

allowed = {
    "bar": foo.bar,
    "baz": foo.baz,
}

func = allowed.get(func_name)
if func:
    func()
else:
    print("Invalid choice")

Comparisons

ApproachHow it worksBest forProsCons
Direct callfoo.bar()Known function namesSimple and clearNot dynamic
getattr()getattr(foo, "bar")()Dynamic lookup on modules or objectsFlexible, built-inCan be unsafe if unrestricted
Dispatch dictionaryhandlers["bar"]()Controlled set of actionsSafe, explicit, readableRequires manual mapping

getattr() vs dispatch dictionary

# getattr
getattr(foo, func_name)()
# dispatch table
DISPATCH = {
    "bar": foo.bar,
    "baz": foo.baz,
}
DISPATCH[func_name]()

Use getattr() when:

  • you genuinely need attribute-based dynamic lookup
  • function names already exist naturally on a module or object

Use a dispatch dictionary when:

  • only certain functions should be callable
  • you want clearer validation
  • you want more maintainable code

Module attribute lookup vs local lookup

If you need to look up a name in the current scope, getattr() is not the usual tool. It is for objects and modules. For object/module attributes, getattr() is the right fit.

Take Quiz

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

  • foo.bar() accesses a known attribute directly
  • foo.func_name() does not use the string value in func_name
  • getattr(foo, func_name) uses the string as the attribute name
  • not every attribute is a function, so callable() can help
  • use a dispatch table when you want a safe list of allowed actions

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.

Should I use getattr() or a dictionary of functions?

Use getattr() for true dynamic attribute lookup. Use a dictionary when you want a controlled and explicit set of allowed actions.

Can this also work with class instances?

Yes. getattr() works on modules, objects, and class instances:

method = getattr(obj, "run")
method()
Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more