Equivalent of __func__ (from C) in Python

折月煮酒 提交于 2019-12-20 10:47:37

问题


I want to create some kind of debugging output for python and want to pass the functionname to another function for output.

The only reasonable way I found to do so was:

def foobar():
  print 'hello world'

  print foobar.__name__

is there something that does the same thing for the current function to improve copy and pasting of that line?

like the C equivalent printf("%s", __func__).


回答1:


sys._getframe can do that:

import sys

def foobar():
    print sys._getframe().f_code.co_name



回答2:


One thing you could try is to create a decorator that does this:

def traceme(func):
  def newfunc(*args, **kwargs):
    ret = func(*args, **kwargs)
    print func.__name__
    return ret
  return newfunc

@traceme
def foobar():
  print 'hello world'



回答3:


Well, yes, there is a way...

print sys._getframe().f_code.co_name

You can even make it a function (getting the name of the previous frame):

def function_name():
    return sys._getframe().f_back.f_code.co_name

Silly example just to show that it works:

>>> def bar():
...     return function_name()
... 
>>> bar()
'bar'

(Note that the decorator shown in Krumelur's answer is a much better solution to the problem, but it is possible to do what you want in Python =)



来源:https://stackoverflow.com/questions/8759359/equivalent-of-func-from-c-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!