【问题标题】:Import * from module by importing via string通过字符串导入从模块导入 *
【发布时间】:2023-04-02 03:14:01
【问题描述】:

我知道我可以使用importlib 通过字符串导入模块。如何使用此库重新创建 import * 功能?基本上,我想要这样的东西:

importlib.import_module('path.to.module', '*')

我不为导入的属性命名空间的原因是故意的。

【问题讨论】:

    标签: python


    【解决方案1】:

    这里有一个解决方案:导入模块,然后在当前命名空间中一个一个地make alias:

    import importlib
    
    # Import the module
    mod = importlib.import_module('collections')
    
    # Determine a list of names to copy to the current name space
    names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])
    
    # Copy those names into the current name space
    g = globals()
    for name in names:
        g[name] = getattr(mod, name)
    

    【讨论】:

      【解决方案2】:

      这里是@HaiVu answer 的缩写版本,指的是this solution from @Bakuriu

      import importlib
      
      # import the module
      mod = importlib.import_module('collections')
      
      # make the variable global
      globals().update(mod.__dict__)
      

      注意:

      • 这将在用户定义的变量之外导入很多东西

      • @HaiVu 解决方案做到了最好,即。只导入用户定义的变量

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-28
        • 2020-08-21
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        相关资源
        最近更新 更多