Last modified: Nov 19, 2026

Python Get Function Name at Runtime

Sometimes you need to know the name of a function while your program is running. This is common in logging, debugging, and building decorators.

Python makes this easy. Every function carries metadata about itself. You just need to know where to look.

This guide shows the most reliable ways to get a function name at runtime. Each method comes with clear examples and output.

Why Get a Function Name at Runtime?

Function names are useful in many situations. They help you build readable logs and error messages.

Decorators often need the wrapped function's name. Test frameworks and profilers also rely on it.

Dynamic code can call functions you did not name in advance. In those cases, printing the name helps you understand what ran.

Let's start with the simplest approach.

Using the __name__ Attribute

Every Python function has a __name__ attribute. It stores the name the function was defined with.

You can access it directly on the function object. This is the fastest and cleanest method.


def greet():
    print("Hello!")

# Access the function name directly
print(greet.__name__)

greet

This works for regular functions, lambdas, and methods. A lambda's name is simply <lambda>.

The __name__ attribute is read-only metadata. It never changes unless you assign to it.


square = lambda x: x * x

# Lambdas have a generic name
print(square.__name__)

For most everyday tasks, this attribute is all you need.

Getting the Name Inside a Function

What if you want the name from inside the function body? You cannot use __name__ directly there.

You could call the function object itself, but that is awkward. A cleaner way is to inspect the call stack.

The inspect module gives you tools to examine live code. When you are working with callables, it pairs well with techniques covered in the Python inspect function signature guide.


import inspect

def current_name():
    # Get the name of the currently running function
    return inspect.currentframe().f_code.co_name

print(current_name())

current_name

The inspect.currentframe() call returns the current frame. The co_name attribute holds the code object's name.

This technique is handy inside helpers. It lets a function report its own name without hardcoding a string.

Getting the Caller's Function Name

Logging helpers often want to know which function called them. The stack frame gives you that too.

Use inspect.stack() to look one level up. Frame index 1 is the caller.


import inspect

def log_message(message):
    # Get the caller's frame (one level up)
    caller = inspect.stack()[1]
    print(f"[{caller.function}] {message}")

def process_data():
    log_message("Starting data processing")

process_data()

[process_data] Starting data processing

Be aware that inspect.stack() is slower than reading a frame directly. Use it when clarity matters more than speed.

For hot code paths, prefer inspect.currentframe().f_back to walk the stack manually.

Using sys._getframe for Speed

The sys._getframe() function is a lightweight alternative. It skips the extra work that inspect.stack() does.

The leading underscore signals that it is an implementation detail. It works on CPython, which is the most common interpreter.


import sys

def fast_caller_name():
    # Walk back one frame to reach the caller
    frame = sys._getframe(1)
    return frame.f_code.co_name

def outer():
    print(fast_caller_name())

outer()

outer

This approach is fast and effective. Just document the CPython dependency if your code must run elsewhere.

Function Names in Decorators

Decorators are the most common place people need function names. A wrapper should preserve the original name.

Without help, the wrapper hides the real function. The functools.wraps helper copies metadata for you.

If you cache results in decorators, see the guide on Python caching with functools for related patterns.


import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # The wrapper now reports the original name
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

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

print(add(2, 3))
print(add.__name__)

Calling add
5
add

Notice that add.__name__ stays add, not wrapper. The functools.wraps call makes that happen.

Without it, the name would be wrapper. That confuses logs and debugging sessions.

For more decorator patterns, read about Python functools: lru_cache and partial. Both tools rely on clean function metadata.

Getting Names from Strings

Sometimes you have a function name as a string. You want to find the function object that matches it.

Use getattr on a module or namespace. It returns the matching object.


import math

# Look up a function by its name as a string
func = getattr(math, "sqrt")
print(func.__name__)
print(func(16))

sqrt
4.0

This is useful for plugin systems and command dispatchers. You store names in config and resolve them at runtime.

Always validate the name first. A wrong string raises AttributeError.

Handling Built-in and Bound Methods

Built-in functions also expose __name__. So do bound methods.


class Counter:
    def increment(self):
        pass

counter = Counter()

# Bound method name
print(counter.increment.__name__)

# Built-in function name
print(len.__name__)

increment
len

Some C-implemented callables lack this attribute. Wrap access in a check when you are unsure.


def safe_name(obj):
    # Fall back to the class name if __name__ is missing
    return getattr(obj, "__name__", type(obj).__name__)

print(safe_name(len))

len

This defensive pattern keeps your code from crashing on unusual objects.

Common Mistakes to Avoid

Do not confuse the function's name with the variable that holds it. They can differ.

In the example below, the variable is f but the name is original.


def original():
    pass

f = original

# The name comes from the definition, not the variable
print(f.__name__)

original

Also avoid calling __name__ on an instance. Instances usually do not have it. Call it on the class or the method instead.

Finally, remember that inspect.stack() can be slow in loops. Cache the result if you call it often.

Quick Reference Table

Here is a short summary of the main approaches.

__name__: best for function objects you already hold. It is fast and simple.

inspect.currentframe(): best for the currently running function. It is readable and portable.

inspect.stack(): best for caller names in logging helpers. It is clear but slower.

sys._getframe(): best for performance-sensitive stack walking on CPython.

getattr(): best when you start with a name string and need the object.

Conclusion

Getting a function name at runtime in Python is straightforward. The __name__ attribute covers most cases.

When you need the name from inside a function, use frame inspection. The inspect module and sys._getframe() both work well.

In decorators, always use functools.wraps to keep names intact. Your logs and tracebacks will thank you.

Pick the method that fits your situation. Start simple, and reach for stack inspection only when you truly need it.