从该函数中确定函数名称(不使用追溯)
  在Python中,如果不使用traceback模块,有没有一种方法可以从该函数中确定函数的名称? 
  假设我有一个带功能栏的模块foo。  执行foo.bar() ,有没有一种方法可以让酒吧知道酒吧的名字?  或者更好, foo.bar的名字? 
#foo.py  
def bar():
    print "my name is", __myname__ # <== how do I calculate this at runtime?
  Python没有功能来访问该函数本身内的函数或其名称。  它已被提出但被拒绝。  如果你不想自己玩堆叠,你应该根据上下文使用"bar"或bar.__name__ 。 
给出的拒绝通知是:
这个PEP被拒绝了。 目前尚不清楚应该如何实施,或者边缘案例中的精确语义应该如何,并且没有给出足够的重要用例。 反应最多也不冷不热。
import inspect
def foo():
   print inspect.stack()[0][3]
有几种方法可以获得相同的结果:
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
上一篇: Determine function name from within that function (without using traceback)
下一篇: What is the best way to remove accents in a Python unicode string?
