问题描述
有些包有一些方法,比如 subscribe
或 add
,让用户添加自定义的回调函数。出于调试目的和好奇心,我想知道这个包中的哪个函数和哪个类稍后实际调用了我的回调函数。所以如果我有课程的行号就好了。
最小工作示例
# test.py
import inspect
class Foo: # line 5
def caller(self):
print("Hello from caller")
b=Bar()
b.func()
class Bar:
def func(self):
print("Hello from func")
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name
# Need some help here to get value 5
# To do
# ...
print(f"Called by {the_class}.{the_method}()")
f = Foo()
f.caller()
输出:
Hello from caller
Hello from func
Called by Foo.caller()
问:在func
里面,如何得到值5,也就是class Foo
定义的行号?理想情况下,通过 inspect
或其他回溯魔法,而不是通过搜索文件中的字符串。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)