You can get a Python function's name as a string with func.__name__ — that is the direct answer and it works for any function object you already hold a reference to. If you are inside the function and want its own name, call inspect.currentframe().f_code.co_name, or wrap the call in a helper that reads the caller's name. Everything below shows each method, when it is the right choice, and where it quietly breaks.

What You'll Need

  • Python 3 installed (any recent 3.x release; the examples use only standard library features).
  • A text editor or IDE and a terminal to run scripts.
  • Basic familiarity with defining functions and importing modules.
  • Nothing to install — inspect, sys and traceback ship with Python.

Step-by-Step

  1. Use __name__ when you have the function object. Define a function and print its name attribute:
    def calculate_tax(amount):
        return amount * 0.2
    
    print(calculate_tax.__name__)   # calculate_tax
    
    This is the cleanest method. It works on plain functions, methods, lambdas (which return <lambda>), and built-ins. It does not work on arbitrary callables such as class instances that define __call__ — those have no __name__ unless you add one.
  2. Get a method's name the same way. Bound methods expose __name__ too:
    class Invoice:
        def total(self):
            return 0
    
    print(Invoice().total.__name__)  # total
    
    If you need the class name as well, use type(obj).__name__ or obj.__class__.__name__.
  3. Get the current function's own name from inside it. Use inspect.currentframe():
    import inspect
    
    def log_event():
        name = inspect.currentframe().f_code.co_name
        print(f"running {name}")
    
    log_event()   # running log_event
    
    The frame object can create reference cycles, so if you store it, delete it afterwards (del frame) or use inspect.stack() sparingly. For a one-line print this is not a concern.
  4. Get the caller's function name. If you are writing a decorator or logger and want the name of the function that called yours, step back one frame:
    import inspect
    
    def who_called_me():
        frame = inspect.currentframe().f_back
        return frame.f_code.co_name
    
    def handler():
        print(who_called_me())
    
    handler()   # handler
    
    This is the standard trick for decorators that need to report the wrapped function's name. Prefer functools.wraps when you only need to preserve the name on the wrapper.
  5. Resolve a name to a function object and back. If you have a string and want the function, use getattr on a module or class:
    import math
    fn = getattr(math, "sqrt")
    print(fn.__name__)   # sqrt
    
    Going the other direction — string to function — is what getattr and globals() are for. Do not use eval for this; it is unsafe with untrusted input.
  6. Handle callables without __name__. For a class instance used as a function, fall back to the type name or a custom attribute:
    class Task:
        def __call__(self):
            pass
    
    t = Task()
    name = getattr(t, "__name__", type(t).__name__)
    print(name)   # Task
    
    This avoids an AttributeError and gives you something meaningful in logs.
  7. Preserve names through decorators. A decorator without functools.wraps replaces the function's name with the wrapper's name:
    import functools
    
    def my_decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            return fn(*args, **kwargs)
        return wrapper
    
    @my_decorator
    def send_alert():
        pass
    
    print(send_alert.__name__)   # send_alert
    
    Without the @functools.wraps(fn) line the output would be wrapper. This is the single most common reason a name looks wrong in production logs.

Common Mistakes

  • Using __name__ on a module instead of a function. module.__name__ gives the module name, not a function name. Check what object you actually have.
  • Forgetting functools.wraps in decorators. The wrapped function then reports the wrapper's name, which breaks logging and debugging.
  • Assuming lambdas have useful names. A lambda's __name__ is the literal string <lambda>. If you need a readable label, assign it to a variable and use that variable's name, or define a real function.
  • Calling inspect.currentframe() in tight loops. Frame inspection is slower than reading __name__; cache the name once if performance matters.
  • Expecting __name__ on partials or built-in method wrappers. Some callables do not expose it; use getattr(obj, "__name__", fallback).
  • Using eval to turn a string into a function. It works but is a security risk; getattr on a known module or a dictionary lookup is safer.

Tips

  • Prefer func.__name__ whenever you already have the function object — it is fast, obvious, and does not touch the call stack.
  • Use inspect.currentframe().f_code.co_name only when you genuinely need the running function's name, such as generic logging helpers.
  • For decorators, combine functools.wraps with inspect if you also need the original name inside the wrapper.
  • If you need the fully qualified name (module plus function), use func.__module__ + "." + func.__qualname__. __qualname__ includes the class path for methods.
  • When logging, include the module and line number alongside the name so you can trace the source quickly.
  • Keep a small helper function like def name_of(fn): return getattr(fn, "__name__", type(fn).__name__) and reuse it instead of scattering getattr calls everywhere.

Troubleshooting

  • AttributeError: 'function' object has no attribute '__name__' — this usually means you are holding a callable object, not a function. Wrap the access in getattr with a fallback.
  • The name is wrapper or inner instead of the real function — a decorator is missing functools.wraps. Add it and re-run.
  • inspect.currentframe() returns None — this can happen in some restricted environments or when the frame has been cleared. Guard with a check and fall back to a static string.
  • The caller's name is wrong when using threads or async code — frame inspection reflects the current call stack, and async tasks can interleave. Capture the name at the point of definition rather than at call time.
  • Name looks correct in a script but wrong in a notebook — notebook cells sometimes wrap code in generated functions. Test the same snippet in a plain .py file to confirm.
  • Performance drops after adding name lookups — move the lookup outside the hot loop, or store the name in a module-level constant.

Frequently Asked Questions

How do I get a function's name as a string in Python?

Use func.__name__ on the function object. For example, print(calculate_tax.__name__) prints calculate_tax.

How do I get the name of the function I am currently inside?

Call inspect.currentframe().f_code.co_name inside the function. It returns the name of the running function as a string.

Why does my decorated function show the wrapper's name?

Because the decorator replaced the original function with a wrapper. Add @functools.wraps(fn) to the wrapper so the original __name__ and docstring are preserved.

Can I get a function's name from a string?

Yes. Use getattr(module, "function_name") to look it up on a module or class. Avoid eval for this, especially with user-supplied input.

What is the name of a lambda function?

It is the literal string <lambda>. Lambdas have no meaningful name, so assign them to a variable or define a regular function if you need a readable label.

Does __name__ work on built-in functions?

Yes, most built-ins expose __name__, for example len.__name__ returns len. Some C-level callables may not, so use getattr with a fallback if you are unsure.