How to get a function name as a string in Python?

In Python, how do I get a function name as a string without calling the function?

def my_function():
    pass

print get_function_name_as_string(my_function) # my_function is not in quotes

should output "my_function" .

Is this available in python? If not, any idea how to write get_function_name_as_string in Python?


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.


你也可以使用

import sys
this_function_name = sys._getframe().f_code.co_name

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. :)

链接地址: http://www.djcxy.com/p/55194.html

上一篇: 什么使用多处理或多

下一篇: 如何在Python中获取函数名称作为字符串?