use*_*311 5 python python-import import-hooks
我正在我的 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__)
Run Code Online (Sandbox Code Playgroud)
在现有的模块中,我有代码检查调用者是否是一个模块
def register(a: str):
caller = inspect.stack()[1]
caller_module = inspect.getmodule(caller[0])
assert caller_module is not None
Run Code Online (Sandbox Code Playgroud)
由于我从运行时模块调用现有模块,因此我预计 caller_module 不是 None 。然而,我确实符合这个断言。不知道为什么。
有人可以帮忙吗?
| 归档时间: |
|
| 查看次数: |
345 次 |
| 最近记录: |