[英]When is __all__ used while importing a module in Python?
Say there is a greetings module like this:假设有一个这样的问候模块:
__all__ = []
def offer(func):
__all__.append(func.__name__)
return func
@offer
def spanish():
return "Hola!"
@offer
def japanese():
return "Konnichiwa"
When does the interpreter decide what to import when from greetings import *
is run?当
from greetings import *
运行时,解释器何时决定导入什么?
When does the interpreter decide what to import when from greetings import * is run?
当 from greetings import * 运行时,解释器何时决定导入什么?
When you say from greetings import *
, interpreter loads and executes the greeting module, then it references the objects mentioned in the __all__
list back into the current module's global namespace so that you can access them using those symbols inside the __all__
.当您说
from greetings import *
时,解释器加载并执行 greeting 模块,然后它将__all__
列表中提到的对象引用回当前模块的全局命名空间,以便您可以使用__all__
中的那些符号访问它们。
I think you guessed because you defined __all__
at the beginning of the module and it's empty, nothing is going to be imported.我想你猜到了,因为你在模块的开头定义了
__all__
并且它是空的,什么都不会被导入。 No that's not the case.不,事实并非如此。
__all__
tells a list of module names that should be imported when from package import *
is encountered. __all__
告诉遇到from package import *
导入的模块名称列表。
For Example, If __all__
is not defined, the statement from greetings.languages import *
does not import all submodules from the package greetings.languages
into the current namespace;例如,如果
__all__
未定义,则from greetings.languages import *
的语句不会将 package greetings.languages
中的所有子模块导入当前命名空间; it only ensures that the package greetings.languages
has been imported (possibly running any initialization code in __init__.py
) and then imports whatever names are defined in the package.它只确保 package
greetings.languages
已被导入(可能在__init__.py
中运行任何初始化代码),然后导入 package 中定义的任何名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.