Skip to main content
 首页 » 编程设计

python之在 Python 中动态加载模块中的所有名称

2024年10月25日8Renyi-Fan

如何from some.module import *,其中模块的名称是在字符串变量中定义的?

请您参考如下方法:

此代码从 os 导入所有符号:

import importlib 
# Load the module as `module' 
module = importlib.import_module("os") 
# Now extract the attributes into the locals() namespace, as `from ..  
# import *' would do 
if hasattr(module, "__all__"): 
    # A module can define __all__ to explicitly define which names 
    # are imported by the `.. import *' statement 
    attrs = { key: getattr(module, key) for key in module.__all__ } 
else: 
    # Otherwise, the statement imports all names that do not start with 
    # an underscore 
    attrs = { key: value for key, value in module.__dict__.items() if 
              key[0] != "_" } 
# Copy the attibutes into the locals() namespace 
locals().update(attrs) 

参见例如this question有关 from ... import * 操作背后逻辑的更多信息。

虽然这有效,但您不应该使用此代码。从命名模块导入所有符号已经被认为是不好的做法,但使用用户给定的名称执行此操作肯定更糟糕。如果您需要有关可能出错的提示,请搜索 PHP 的 register_globals。