如何从 Python 函数或方法中获取函数或方法的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/245304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:43:51  来源:igfitidea点击:

How do I get the name of a function or method from within a Python function or method?

python

提问by Daryl Spitzer

I feel like I should know this, but I haven't been able to figure it out...

我觉得我应该知道这一点,但我一直无法弄清楚......

I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

我想从它内部获取方法的名称——它恰好是一个集成测试——以便它可以打印出一些诊断文本。当然,我可以在字符串中硬编码方法的名称,但如果可能的话,我想让测试更加干燥。

采纳答案by spiv

The answers involving introspection via inspectand the like are reasonable. But there may be another option, depending on your situation:

涉及introspection viainspect等的答案是合理的。但可能还有另一种选择,具体取决于您的情况:

If your integration test is written with the unittestmodule, then you could use self.id()within your TestCase.

如果您的集成测试是使用unittest模块编写的,那么您可以self.id()在您的 TestCase 中使用。

回答by mhawke

This seems to be the simplest way using module inspect:

这似乎是使用 module 的最简单方法inspect

import inspect
def somefunc(a,b,c):
    print "My name is: %s" % inspect.stack()[0][3]

You could generalise this with:

您可以将其概括为:

def funcname():
    return inspect.stack()[1][3]

def somefunc(a,b,c):
    print "My name is: %s" % funcname()

Credit to Stefaan Lippenswhich was found via google.

感谢斯特凡Lippens这是通过谷歌找到。

回答by nosklo

This decorator makes the name of the method available inside the function by passing it as a keyword argument.

此装饰器通过将其作为关键字参数传递,使该方法的名称在函数内可用。

from functools import wraps
def pass_func_name(func):
    "Name of decorated function will be passed as keyword arg _func_name"
    @wraps(func)
    def _pass_name(*args, **kwds):
        kwds['_func_name'] = func.func_name
        return func(*args, **kwds)
    return _pass_name

You would use it this way:

你会这样使用它:

@pass_func_name
def sum(a, b, _func_name):
    print "running function %s" % _func_name
    return a + b

print sum(2, 4)

But maybe you'd want to write what you want directly inside the decorator itself. Then the code is an example of a way to get the function name in a decorator. If you give more details about what you want to do in the function, that requires the name, maybe I can suggest something else.

但也许您想直接在装饰器内部编写您想要的内容。然后代码是在装饰器中获取函数名称的方法示例。如果您提供有关您想在函数中执行的操作的更多详细信息,则需要名称,也许我可以提出其他建议。

回答by Kevin Little

# file "foo.py" 
import sys
import os

def LINE( back = 0 ):
    return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
    return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
    return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
    frame = sys._getframe( back + 1 )
    return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),     
                            frame.f_lineno, frame.f_code.co_name )

def testit():
   print "Here in %s, file %s, line %s" % ( FUNC(), FILE(), LINE() )
   print "WHERE says '%s'" % WHERE()

testit()

Output:

输出:

$ python foo.py
Here in testit, file foo.py, line 17
WHERE says 'foo.py/18 testit()'

Use "back = 1" to find info regarding two levels back down the stack, etc.

使用“back = 1”来查找有关返回堆栈的两个级别的信息等。

回答by Greg Hewgill

I think the tracebackmodule might have what you're looking for. In particular, the extract_stackfunction looks like it will do the job.

我认为该traceback模块可能具有您正在寻找的内容。特别是,该extract_stack功能看起来可以完成这项工作。