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,sysandtracebackship with Python.
Step-by-Step
- Use
__name__when you have the function object. Define a function and print its name attribute:
This is the cleanest method. It works on plain functions, methods, lambdas (which returndef calculate_tax(amount): return amount * 0.2 print(calculate_tax.__name__) # calculate_tax<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. - Get a method's name the same way. Bound methods expose
__name__too:
If you need the class name as well, useclass Invoice: def total(self): return 0 print(Invoice().total.__name__) # totaltype(obj).__name__orobj.__class__.__name__. - Get the current function's own name from inside it. Use
inspect.currentframe():
The frame object can create reference cycles, so if you store it, delete it afterwards (import inspect def log_event(): name = inspect.currentframe().f_code.co_name print(f"running {name}") log_event() # running log_eventdel frame) or useinspect.stack()sparingly. For a one-line print this is not a concern. - 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:
This is the standard trick for decorators that need to report the wrapped function's name. Preferimport inspect def who_called_me(): frame = inspect.currentframe().f_back return frame.f_code.co_name def handler(): print(who_called_me()) handler() # handlerfunctools.wrapswhen you only need to preserve the name on the wrapper. - Resolve a name to a function object and back. If you have a string and want the function, use
getattron a module or class:
Going the other direction — string to function — is whatimport math fn = getattr(math, "sqrt") print(fn.__name__) # sqrtgetattrandglobals()are for. Do not useevalfor this; it is unsafe with untrusted input. - Handle callables without
__name__. For a class instance used as a function, fall back to the type name or a custom attribute:
This avoids anclass Task: def __call__(self): pass t = Task() name = getattr(t, "__name__", type(t).__name__) print(name) # TaskAttributeErrorand gives you something meaningful in logs. - Preserve names through decorators. A decorator without
functools.wrapsreplaces the function's name with the wrapper's name:
Without theimport 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@functools.wraps(fn)line the output would bewrapper. 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.wrapsin 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; usegetattr(obj, "__name__", fallback). - Using
evalto turn a string into a function. It works but is a security risk;getattron 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_nameonly when you genuinely need the running function's name, such as generic logging helpers. - For decorators, combine
functools.wrapswithinspectif 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 scatteringgetattrcalls 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
getattrwith a fallback. - The name is
wrapperorinnerinstead of the real function — a decorator is missingfunctools.wraps. Add it and re-run. inspect.currentframe()returnsNone— 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
.pyfile 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.