从函数内部访问模块属性



我有一个函数,完全限定名是->pyserv.asynch.service.modules.get_result()

pyserv或其他模块(如servicesmodules)可能在运行时添加了属性。

有可能在运行时设置了以下选项之一

pyserv._service = "call"
services._service = "mode"
modules._service = "test"

用户可以使用->service.modules.get_result()modules.get_result()。在这种情况下,我希望得到"服务"。get_result()方法中直接调用方模块的值。

我尝试使用inspect API。但我只能得到调用者,而不能得到模块。谁能建议如何解决这个问题?

您应该能够像这样获得它:

import inspect
def get_result():
frame = inspect.currentframe()
caller_frame = frame.f_back
caller_mod = inspec.getmodule(caller_frame) # <--- this is the module where get_result() was called.

最新更新