如何读取Python中import语句使用的模块别名?
获取Python模块导入别名的方法
首先明确:Python的模块对象本身不会存储它被导入时绑定的别名,__name__属性返回的是模块的原始名称,这是设计上的特性——变量别名只是当前作用域里指向模块对象的引用,模块本身不知道自己被哪个名字引用。
下面是两种可行的解决思路:
1. 手动维护别名映射表(推荐)
自己定义一个字典,把别名和对应的模块对象关联起来,之后直接通过这个字典查询,这种方式最可靠:
import awesome as custom_import_name import woot as custom_second_name # 手动创建别名-模块的映射 module_aliases = { "custom_import_name": custom_import_name, "custom_second_name": custom_second_name } # 根据模块对象查找别名 target_module = custom_import_name for alias, module in module_aliases.items(): if module is target_module: print(alias) # 输出 custom_import_name
2. 遍历当前作用域的变量(慎用)
通过globals()或locals()遍历当前作用域的变量,找到指向目标模块对象的变量名。但这种方法有局限性:如果同一个模块被绑定到多个别名,或者有其他变量指向该模块对象,只会返回第一个匹配的名字:
import awesome as custom_import_name import woot as custom_second_name def find_module_alias(module): # 遍历全局作用域的变量,排除内置特殊变量 for name, obj in globals().items(): if obj is module and not name.startswith("__"): return name return None print(find_module_alias(custom_import_name)) # 输出 custom_import_name print(find_module_alias(custom_second_name)) # 输出 custom_second_name
总结
没有内置方法可以直接获取模块的导入别名,因为模块对象和引用它的变量名是分离的。最稳妥的方案是手动维护别名映射表,避免依赖作用域遍历带来的不确定性。
内容的提问来源于stack exchange,提问作者Gaspar
相关产品推荐
相关产品推荐

