How to get a function name as a string?
To get the current function's or method's 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 function's 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
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.
If you're interested in class methods too, Python 3.3+ has __qualname__
in addition to __name__
.
def my_function():
pass
class MyClass(object):
def method(self):
pass
print(my_function.__name__) # gives "my_function"
print(MyClass.method.__name__) # gives "method"
print(my_function.__qualname__) # gives "my_function"
print(MyClass.method.__qualname__) # gives "MyClass.method"
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. :)