python – How to get a function name as a string?
python – How to get a function name as a string?
my_function.__name__
Using __name__
is the preferred method as it applies uniformly. Unlike func_name
, it works on built-in functions as well:
>>> import time
>>> time.time.func_name
Traceback (most recent call last):
File <stdin>, line 1, in ?
AttributeError: builtin_function_or_method object has no attribute func_name
>>> time.time.__name__
time
Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__
attribute too, so you only have remember one special name.
To get the current functions or methods name from inside it, consider:
import inspect
this_function_name = inspect.currentframe().f_code.co_name
sys._getframe
also works instead of inspect.currentframe
although the latter avoids accessing a private function.
To get the calling functions name instead, consider f_back
as in inspect.currentframe().f_back.f_code.co_name
.
If also using mypy
, it can complain that:
error: Item None of Optional[FrameType] has no attribute f_code
To suppress the above error, consider:
import inspect
import types
from typing import cast
this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name
python – How to get a function name as a string?
my_function.func_name
There are also other fun properties of functions. Type dir(func_name)
to list them. func_name.func_code.co_code
is the compiled function, stored as a string.
import dis
dis.dis(my_function)
will display the code in almost human readable format. 🙂