In Python, how do I get a function name as a string without calling the function?
在Python中,如何在不调用函数的情况下将函数名作为字符串获取?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
should output "my_function"
.
应该输出“my_function”。
Is this available in python? If not, any idea how to write get_function_name_as_string
in Python?
这在python中可用吗?如果没有,您知道如何在Python中编写get_function_name_as_string吗?
9 个解决方案
#1
581
my_function.__name__
Using __name__
is the preferred method as it applies uniformly. Unlike func_name
, it works on built-in functions as well:
使用__name__是首选的方法,因为它是统一应用的。与func_name不同,它也在内置函数上工作:
>>> 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.
另外,双下划线向读者表明这是一个特殊的属性。另外,类和模块也有一个__name__属性,所以您只能记住一个特殊的名称。
#2
194
You could also use
您还可以使用
import sys
this_function_name = sys._getframe().f_code.co_name
#3
36
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.
函数还有其他有趣的性质。键入dir(func_name)以列出它们。func_name.func_code。co_code是编译后的函数,存储为字符串。
import dis
dis.dis(my_function)
will display the code in almost human readable format. :)
将以几乎人类可读的格式显示代码。:)
#4
28
This function will return the caller's function name.
这个函数将返回调用者的函数名。
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
It is like Albert Vonpupp's answer with a friendly wrapper.
这就像阿尔伯特·冯普普用友好的包装来回答问题。
#5
10
sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.
sys._getframe()不能保证在Python的所有实现中都可用(请参阅ref),您可以使用traceback模块做同样的事情,例如。
import traceback
def who_am_i():
stack = traceback.extract_stack()
filename, codeline, funcName, text = stack[-2]
return funcName
A call to stack[-1] will return the current process details.
调用stack[-1]将返回当前进程的详细信息。
#6
8
If you're interested in class methods too, Python 3.3+ has __qualname__
in addition to __name__
.
如果您也对类方法感兴趣,那么除了__name__之外,Python 3.3+还有__qualname__。
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"
#7
7
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
我喜欢使用函数修饰符。我添加了一个类,它也乘以函数时间。假设gLog是一个标准的python日志记录器:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
现在你要做的就是装饰你的函数
@func_timer_decorator
def my_func():
#8
6
As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:
作为@Demyn的答案的扩展,我创建了一些实用函数来打印当前函数的名称和当前函数的参数:
import inspect
import logging
import traceback
def get_function_name():
return traceback.extract_stack(None, 2)[0][2]
def get_function_parameters_and_values():
frame = inspect.currentframe().f_back
args, _, _, values = inspect.getargvalues(frame)
return ([(i, values[i]) for i in args])
def my_func(a, b, c=None):
logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
pass
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])
#9
1
You just want to get the name of the function here is a simple code for that. let say you have these functions defined
你只需要得到函数名这里有一个简单的代码。假设你定义了这些函数
def function1():
print "function1"
def function2():
print "function2"
def function3():
print "function3"
print function1.__name__
the output will be function1
输出是function1
Now let say you have these functions in a list
现在假设你在一个列表中有这些函数
a = [function1 , function2 , funciton3]
to get the name of the functions
获取函数的名称。
for i in a:
print i.__name__
the output will be
输出将
function1
function2
function3
function1 function2 function3
#1
581
my_function.__name__
Using __name__
is the preferred method as it applies uniformly. Unlike func_name
, it works on built-in functions as well:
使用__name__是首选的方法,因为它是统一应用的。与func_name不同,它也在内置函数上工作:
>>> 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.
另外,双下划线向读者表明这是一个特殊的属性。另外,类和模块也有一个__name__属性,所以您只能记住一个特殊的名称。
#2
194
You could also use
您还可以使用
import sys
this_function_name = sys._getframe().f_code.co_name
#3
36
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.
函数还有其他有趣的性质。键入dir(func_name)以列出它们。func_name.func_code。co_code是编译后的函数,存储为字符串。
import dis
dis.dis(my_function)
will display the code in almost human readable format. :)
将以几乎人类可读的格式显示代码。:)
#4
28
This function will return the caller's function name.
这个函数将返回调用者的函数名。
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
It is like Albert Vonpupp's answer with a friendly wrapper.
这就像阿尔伯特·冯普普用友好的包装来回答问题。
#5
10
sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.
sys._getframe()不能保证在Python的所有实现中都可用(请参阅ref),您可以使用traceback模块做同样的事情,例如。
import traceback
def who_am_i():
stack = traceback.extract_stack()
filename, codeline, funcName, text = stack[-2]
return funcName
A call to stack[-1] will return the current process details.
调用stack[-1]将返回当前进程的详细信息。
#6
8
If you're interested in class methods too, Python 3.3+ has __qualname__
in addition to __name__
.
如果您也对类方法感兴趣,那么除了__name__之外,Python 3.3+还有__qualname__。
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"
#7
7
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
我喜欢使用函数修饰符。我添加了一个类,它也乘以函数时间。假设gLog是一个标准的python日志记录器:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
现在你要做的就是装饰你的函数
@func_timer_decorator
def my_func():
#8
6
As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:
作为@Demyn的答案的扩展,我创建了一些实用函数来打印当前函数的名称和当前函数的参数:
import inspect
import logging
import traceback
def get_function_name():
return traceback.extract_stack(None, 2)[0][2]
def get_function_parameters_and_values():
frame = inspect.currentframe().f_back
args, _, _, values = inspect.getargvalues(frame)
return ([(i, values[i]) for i in args])
def my_func(a, b, c=None):
logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
pass
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])
#9
1
You just want to get the name of the function here is a simple code for that. let say you have these functions defined
你只需要得到函数名这里有一个简单的代码。假设你定义了这些函数
def function1():
print "function1"
def function2():
print "function2"
def function3():
print "function3"
print function1.__name__
the output will be function1
输出是function1
Now let say you have these functions in a list
现在假设你在一个列表中有这些函数
a = [function1 , function2 , funciton3]
to get the name of the functions
获取函数的名称。
for i in a:
print i.__name__
the output will be
输出将
function1
function2
function3
function1 function2 function3