简体   繁体   English

在 Python 中导入模块时,何时使用 __all__?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM