Python3中star导入的函数形式是什么

What is the function form of star import in Python 3

Python 中的 import * 使用函数(大概来自 importlib)的等价物是什么?

我知道您可以使用 mod = __import__(...) 导入模块,它将委托给当前配置的任何实现。你也可以这样做

mod_spec = importlib.utl.spec_from_file_location(...)
mod = importlib.util.module_from_spec(mod_spec)
mod_spec.loader.exec_module(mod)

这允许你做一些疯狂的事情,比如通过在调用 exec_module 之前插入它们来将它们注入模块。 (由 and 提供)

但是,我的问题仍然存在。 import * 在函数形式中是如何工作的?哪个函数根据 __all__ 的 presence/contents 决定从模块加载哪些名称?

from whatever import * 没有函数。事实上,import whatever 也没有任何功能!当你这样做时

mod = __import__(...)

__import__函数只负责部分工作。它为您提供了一个模块对象,但您必须将该模块对象单独分配给一个变量。没有函数可以像 import whatever 那样导入模块 并且 将其分配给变量。


from whatever import *中,有两部分:

  • whatever
  • 准备模块对象
  • 分配变量

“准备模块对象”部分与 import whatever 中几乎相同,并且可以由相同的函数处理,__import__import * 将加载包的 __all__ 列表中的任何 not-yet-loaded 子模块;如果您提供 fromlist=['*']:

__import__ 将为您处理
module = __import__('whatever', fromlist=['*'])

关于分配名称的部分是最大的不同之处,同样,您必须自己处理。只要您在全球范围内,它就相当简单:

if hasattr(module, '__all__'):
    all_names = module.__all__
else:
    all_names = [name for name in dir(module) if not name.startswith('_')]

globals().update({name: getattr(module, name) for name in all_names})

函数作用域不支持分配运行时确定的变量。