Python:如何在被调用的方法中获取调用者的方法名称?
假设我有两种方法:
def method1(self):
...
a = A.method2()
def method2(self):
...
如果我不想对method1进行任何更改,如何在方法2中获取调用者的名称(在此示例中,名称为method1)?
答案 0 :(得分:185)
inspect.getframeinfo以及inspect
中的其他相关功能可以提供帮助:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
这种内省旨在帮助调试和开发;不建议将其用于生产功能目的。
答案 1 :(得分:75)
更短的版本:
import inspect
def f1(): f2()
def f2():
print 'caller name:', inspect.stack()[1][3]
f1()
(感谢@Alex和Stefaan Lippen)
答案 2 :(得分:42)
这似乎工作正常:
import sys
print sys._getframe().f_back.f_code.co_name
答案 3 :(得分:25)
我想出了一个稍微长一点的版本,试图建立一个完整的方法名称,包括模块和类。
https://gist.github.com/2151727(rev 9cccbf)
# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2
import inspect
def caller_name(skip=2):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
stack = inspect.stack()
start = 0 + skip
if len(stack) < start + 1:
return ''
parentframe = stack[start][0]
name = []
module = inspect.getmodule(parentframe)
# `modname` can be None when frame is executed directly in console
# TODO(techtonik): consider using __main__
if module:
name.append(module.__name__)
# detect classname
if 'self' in parentframe.f_locals:
# I don't know any way to detect call from the object method
# XXX: there seems to be no way to detect static method call - it will
# be just a function call
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append( codename ) # function or a method
## Avoid circular refs and frame leaks
# https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
del parentframe, stack
return ".".join(name)
答案 4 :(得分:10)
上述内容合并的一点点。但这是我对它的抨击。
def print_caller_name(stack_size=3):
def wrapper(fn):
def inner(*args, **kwargs):
import inspect
stack = inspect.stack()
modules = [(index, inspect.getmodule(stack[index][0]))
for index in reversed(range(1, stack_size))]
module_name_lengths = [len(module.__name__)
for _, module in modules]
s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
callers = ['',
s.format(index='level', module='module', name='name'),
'-' * 50]
for index, module in modules:
callers.append(s.format(index=index,
module=module.__name__,
name=stack[index][3]))
callers.append(s.format(index=0,
module=fn.__module__,
name=fn.__name__))
callers.append('')
print('\n'.join(callers))
fn(*args, **kwargs)
return inner
return wrapper
使用:
@print_caller_name(4)
def foo():
return 'foobar'
def bar():
return foo()
def baz():
return bar()
def fizz():
return baz()
fizz()
输出
level : module : name
--------------------------------------------------
3 : None : fizz
2 : None : baz
1 : None : bar
0 : __main__ : foo
答案 5 :(得分:7)
我会使用 inspect.currentframe().f_back.f_code.co_name
。先前的任何答案都未涵盖其使用,这些答案主要是以下三种类型之一:
inspect.stack
,但众所周知也使用slow。sys._getframe
是内部私有函数,鉴于其前导下划线,因此不建议使用。inspect.getouterframes(inspect.currentframe(), 2)[1][3]
,但目前还不清楚[1][3]
正在访问什么。 import inspect
import types
from typing import cast
def caller_name() -> str:
"""Return the calling function's name."""
# Ref: https://stackoverflow.com/a/57712700/
return cast(types.FrameType, inspect.currentframe()).f_back.f_code.co_name
if __name__ == '__main__':
def _test_caller_name() -> None:
assert caller_name() == '_test_caller_name'
_test_caller_name()
致谢:1313e之前对answer作了评论。
答案 6 :(得分:1)
如果您跨越类并希望方法所属的类和方法,我找到了一种方法。它需要一些提取工作,但它是重点。这适用于Python 2.7.13。
import inspect, os
class ClassOne:
def method1(self):
classtwoObj.method2()
class ClassTwo:
def method2(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print '\nI was called from', calframe[1][3], \
'in', calframe[1][4][0][6: -2]
# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()
# start the program
os.system('cls')
classoneObj.method1()
答案 7 :(得分:0)
您可以在此处https://stackoverflow.com/a/56897183/4039061
打印类似功能的列表import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])
答案 8 :(得分:-1)
" "