You get the current function name as a string with inspect.currentframe().f_code.co_name, which returns the name of the function that is running right now. For most day-to-day use, wrapping that in a tiny helper is cleaner, and Python also gives you two shortcuts: __name__ inside a function refers to its own name, and sys._getframe(0).f_code.co_name gives the same result without importing inspect. The method you pick depends on whether you want the name of the current function or of the caller, and on whether you are inside a class method, a decorator, or a module-level script.
What You'll Need
- A working Python 3 installation. The standard library modules used here (
inspectandsys) ship with Python, so nothing needs installing. - A text editor or IDE to write and run a short script.
- Comfort with defining and calling functions, since every example below is a small function.
Step-by-Step
- Start with the simplest shortcut inside a plain function. Every function object carries a
__name__attribute, and inside the function body the name__name__resolves to the function's own name. Create a file calledname_demo.pyand write:
Running it printsdef greet(): print(__name__) greet()greet. This works and it is the cheapest option, but it has a catch: inside a normal function,__name__actually resolves to the module's global__name__if the function does not define its own. That means at script level it prints__main__, not the function name. Test this before you rely on it, and see Common Mistakes below. - Use
inspectfor the reliable answer. Replace the body with the stack-frame approach:
This printsimport inspect def greet(): print(inspect.currentframe().f_code.co_name) greet()greetevery time, because the frame object for the currently executing code holds a code object, andco_nameis the function's name as a string. Theinspectmodule is part of the standard library, so no installation step is required. - Wrap it in a helper so you only write the long line once. Add a small utility to your project:
Be aware that the helper reports its own name if you call it naively from inside another function? No, it reportsimport inspect def current_function_name(): return inspect.currentframe().f_code.co_name def process(): print(f"Running {current_function_name()}") process()current_function_nameonly when invoked directly at that point; from insideprocess,inspect.currentframe()inside the helper returns the helper's frame, so the name printed would becurrent_function_name. To get the caller's name instead, jump one frame back, which is the next step. - Get the caller's name with
f_back. Each frame links to the frame that called it:
This printsimport inspect def caller_name(): return inspect.currentframe().f_back.f_code.co_name def handler(): print(caller_name()) handler()handler. This pattern is what most logging and debugging helpers in the wild are built on. Chain anotherf_backif you need the caller's caller, but do not go deeper than you need: each hop is another frame you must keep straight. - Use the
sysalternative when you want to avoidinspect. Thesysmodule exposes the current frame directly:
This printsimport sys def run_job(): print(sys._getframe().f_code.co_name) run_job()run_job. The leading underscore signals that_getframeis a CPython implementation detail rather than a guaranteed language feature. It works in CPython and PyPy, but for code that must be maximally portable, preferinspect. Also note that passing0gives the current frame and1gives the caller. - Handle method names and decorated functions correctly. Inside a class method, the techniques above return the method's own name, such as
save, notAccount.save. If you need the qualified form, use__qualname__instead:
This printsclass Account: def save(self): print(self.save.__qualname__)Account.save. When a decorator wraps a function, the wrapper's frame is the one on the stack, so the frame approach reports the wrapper's name. Applyfunctools.wrapsto the wrapper so the wrapper copies the wrapped function's metadata, which matters more for__name__than for the frame approach. - Clean up the frame references. Frame objects keep references to their locals and can create reference cycles. If you hold a frame in a variable, delete it when you are done:
In small scripts this rarely matters, but in a long-running service that calls the helper constantly, explicit cleanup avoids keeping frames alive longer than necessary.import inspect def whoami(): frame = inspect.currentframe() try: return frame.f_code.co_name finally: del frame - Test it at the edges. Call your helper from module level, from inside a loop, from a lambda, and from a nested function. A lambda reports
<lambda>rather than a useful name, and module-level code reports<module>. Knowing these outputs in advance stops confusing bugs later. Store the working pattern in a small utilities module so every file in the project imports the same version.
Common Mistakes
The most frequent trap is assuming __name__ inside a function gives the function name. In a normal function it resolves through the global namespace to the module's __name__, which is __main__ in a directly run script or the module's dotted path when imported. It only behaves as a function-name shortcut in limited contexts, so verify it with your own test before shipping code that depends on it.
The second trap is frame confusion in helpers. If a utility function calls inspect.currentframe(), the name returned is the utility's own, because that utility occupies the current frame. People then blame the technique for being wrong when they simply needed f_back. Draw the call stack out on paper: current frame is the code executing the line, f_back is its caller, f_back.f_back is the caller's caller.
A third mistake is assuming _getframe is guaranteed everywhere. It is a CPython detail. Code that may run on other interpreters, or that is packaged for multiple runtimes, should use inspect and keep the sys shortcut as an optimisation only after measuring.
Finally, people forget decorators. Once a function is wrapped, the running frame belongs to the wrapper, so names reported from inside look like the wrapper's name. Use functools.wraps and, where the exact wrapped name matters, read __wrapped__.__name__.
Tips
- Build one
utils.pywith acurrent_function_name()and acaller_name()helper. Consistency beats copying the one-liner into every file. - Use the function name in log messages, for example
logger.debug("entered %s", name). It makes grepping logs dramatically easier than scanning by line number. - Prefer
__qualname__when you want class-qualified names such asOrder.total; it is clearer in reports and dashboards than a bare method name. - Reserve the techniques for diagnostics. Building application logic around frame inspection makes code brittle and hard to reason about.
- When performance matters, cache the name once at function definition rather than inspecting frames on every call; frames are cheap but not free.
Troubleshooting
It prints __main__. You are using __name__ at module level or inside a plain function where it resolves globally. Switch to inspect.currentframe().f_code.co_name.
It prints the helper's name instead of my function's. Your helper is reading its own frame. Add f_back to step out one level, or pass the value in from the calling function.
It prints <lambda> or <module>. That is correct behaviour. Lambdas and module bodies have no meaningful name, so give them one another way, such as passing a label string explicitly.
It breaks under a decorator. The wrapper runs, not your function. Apply functools.wraps and adjust the frame depth to account for the extra layer.
Import error for inspect or sys. That should not happen in any standard Python install. Check that you are not running a file named inspect.py or sys.py in your project directory, which shadows the standard library. Rename the file and delete any leftover .pyc cache.
Frequently Asked Questions
Does this work in Python 2?
The inspect and sys frame attributes exist in Python 2 as well, but Python 2 is long out of support. Use Python 3, where the examples above are tested patterns.
Can I get the file name and line number too?
Yes. The frame's code object has co_filename for the file, and f_lineno on the frame gives the current line. That trio is the basis of most custom log formatters.
Why is the name different from what I defined?
If the function was assigned to another name, decorated, or defined as a lambda, the reported name reflects the underlying code object, not the variable holding it. Check for decorators and aliases first.
Is frame inspection safe in production code?
It is safe to read, but it ties code to interpreter internals and couples logic to call structure. Use it for logging and diagnostics, not for business rules.
Does f_back exist for the outermost frame?
No. At the top of the stack, f_back is None, so guard against it with a check before reading f_code.