python - 如何获取python调用者对象信息?

标签 python introspection

如何从函数中获取调用者对象,并检查有关该调用者的信息?

class A(object):
    def class_A_fun(self):
            print 'caller from class'  # → B
            print 'caller from method'  # → class_B_fun
            print 'caller module'  # → foomodule
            print 'caller instance'  # → obj
            print 'caller object file name or path'  # → 'foomodule.py'

class B(object):
    def class_B_fun(self):    
        obj = A()
        obj.class_A_fun()        

if __name__ == "__main__":
    obj = B()
    obj.class_B_fun()

最佳答案

from inspect import currentframe, getframeinfo, getmodulename
from pathlib import Path


class A(object):
    def class_A_fun(self):
        cuurent_frame = currentframe()
        caller_frame = cuurent_frame.f_back
        filename, lineno, function, code_context, index = getframeinfo(caller_frame)

        # first_arg_name in this case is 'self', but could be sth else
        first_arg_name = caller_frame.f_code.co_varnames[0]
        # f_locals is the local namespace seen by the frame
        caller_instance = caller_frame.f_locals[first_arg_name]

        assert caller_instance is caller_frame.f_back.f_locals['b'] is b
        assert type(caller_instance).__name__ == 'B'
        assert function == caller_frame.f_code.co_name == 'class_B_fun'
        assert filename == caller_frame.f_code.co_filename == __file__
        assert getmodulename(filename) == Path(__file__).stem


class B(object):

    def class_B_fun(self):
        a = A()
        a.class_A_fun()


if __name__ == "__main__":
    b = B()
    b.class_B_fun()

关于python - 如何获取python调用者对象信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997687/

相关文章:

haskell - :t in ghci access all that introspective information?是怎么回事

debugging - 从协程内省(introspection) _ENV

ember.js - 使用 DS.RESTAdapter 检查或内省(introspection) Ember 数据源的便捷方式

objective-c - 有没有办法从方法结构中获取参数的类类型?

javascript - 将对象的属性和值转换为键值对数组

python - 如果两个日期时间都存在于 pandas DataFrame 中,则计算两个日期时间之间的差异

使用 QueueHandler 和 QueueListener 的 Python 日志记录 (logutils)

python - BeautifulSoup 导航忽略指定路径

python - Django Rest框架,从其他模型数组创建模型

python - 修剪 matplotlib 功率谱图