从函数内部确定函数名称(不使用traceback)

2024-04-19 08:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,不使用traceback模块,是否有方法从函数中确定函数名?

假设我有一个带函数条的模块foo。在执行foo.bar()时,是否有方法让bar知道bar的名称?或者更好,foo.bar的名字?

#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?

Tags: 模块方法函数namepy名称foois
3条回答
import inspect

def foo():
   print(inspect.stack()[0][3])
   print(inspect.stack()[1][3]) #will give the caller of foos name, if something called foo

有几种方法可以得到相同的结果:

from __future__ import print_function
import sys
import inspect

def what_is_my_name():
    print(inspect.stack()[0][0].f_code.co_name)
    print(inspect.stack()[0][3])
    print(inspect.currentframe().f_code.co_name)
    print(sys._getframe().f_code.co_name)

请注意,inspect.stack调用比替代调用慢数千倍:

$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][0].f_code.co_name'
1000 loops, best of 3: 499 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.stack()[0][3]'
1000 loops, best of 3: 497 usec per loop
$ python -m timeit -s 'import inspect, sys' 'inspect.currentframe().f_code.co_name'
10000000 loops, best of 3: 0.1 usec per loop
$ python -m timeit -s 'import inspect, sys' 'sys._getframe().f_code.co_name'
10000000 loops, best of 3: 0.135 usec per loop

Python没有访问函数或函数内函数名的功能。已被proposed拒绝。如果您不想自己使用堆栈,则应根据上下文使用"bar"bar.__name__

给出的拒绝通知是:

This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.

相关问题 更多 >