假设我有两个Python模块a和b。
a.py:
CONSTANT = 2
b.py:
from a import CONSTANT
CONSTANT2 = 4
如果我使用
b.__dict__
或
inspect.getmembers(b)
我得到了 CONSTANT 和 CONSTANT2,但是如何只得到 CONSTANT(导入)及其父模块?或者我如何过滤结果以仅获取 CONSTANT 及其父模块?
我最终想要的实际上是“a”,b从中导入的模块
inspect.getmodule(CONSTANT)
不适用于整数或列表
我需要此信息来检查依赖关系是否得到尊重,并且较低级别的模块不会从较高级别的模块导入
要实现您正在寻找的内容,您可以检查模块中导入常量的
__module__
属性 b.py
import a
from a import CONSTANT
import b
import inspect
# Get the module of CONSTANT
constant_module = CONSTANT.__module__
# Filter out the imported constants that belong to module 'a'
imported_constants = {name: obj for name, obj in b.__dict__.items() if getattr(obj, '__module__', None) == constant_module}
# Print the imported constants and their parent module
for name, obj in imported_constants.items():
print(f"{name}: {obj}, imported from module: {constant_module}")
# Alternatively, you can directly get the parent module of CONSTANT using inspect
parent_module = inspect.getmodule(CONSTANT).__name__
print("Parent module of CONSTANT:", parent_module)
此代码片段将帮助您识别从模块
a
到模块 b
中导入的常量,以及它们的父模块 (a
)。它还演示了如何使用 CONSTANT
直接获取 inspect.getmodule(CONSTANT).__name__
的父模块。