How to get a function name as a string?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping
--
Chapters
00:00 How To Get A Function Name As A String?
00:13 Answer 1 Score 48
00:39 Accepted Answer Score 1379
01:14 Answer 3 Score 432
01:56 Answer 4 Score 53
02:15 Thank you
--
Full question
https://stackoverflow.com/questions/2514...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #function
#avk47
ACCEPTED ANSWER
Score 1379
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.
ANSWER 2
Score 432
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
ANSWER 3
Score 53
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"
ANSWER 4
Score 48
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. :)