我正在我的 python 代码中创建一个运行时模块,类似于
string_code = """
import existing_module
a = "my_string"
existing_module.register(a)
"""
mod = ModuleType("mymodule")
sys.modules["mymodule"] = mod
exec(string_code, mod.__dict__)
在现有模块中,我有代码检查调用者是否是模块
def register(a: str):
caller = inspect.stack()[1]
caller_module = inspect.getmodule(caller[0])
assert caller_module is not None
由于我从运行时模块调用 existing_module,我希望 caller_module 不是 None。但是,我正在打那个断言。不知道为什么。
任何人都可以帮忙吗?