为什么要在python包的__init__中使用__all__? [英] Why should I use __all__ in __init__ of python package?

查看:104
本文介绍了为什么要在python包的__init__中使用__all__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有人可以在Python中解释__all__吗?并且我知道它只会影响from ... import *语句,但是我无法弄清楚真正的用例.当我可以避免在__init__名称空间中导入这些名称时,为什么要在__all__中重复导出的名称(DRY!)?

I've already read Can someone explain __all__ in Python? and I understand that it only affects from ... import * statements, but I can't figure out a real use case. Why should I repeat exported names in __all__ (DRY!) when I could simply avoid importing those names in __init__ namespace?

示例:

mypackage/__init__.py

from a import A

mypackage/a.py

A = "A"
A1 = "A1"

mypackage/b.py

B = "B"    

然后在python中

>>> from mypackage import *
>>> A
'A'
>>> 
>>> A1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A1' is not defined
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

您可以看到A在名称空间中,但A1b不在名称空间中.为什么我必须定义__all__ = ["A"]?

As you can see A is in the namespace but A1 and b are not. Why should I have to define __all__ = ["A"]?

推荐答案

要在包__init__.py中定义__all__ only 时间是列出已导出"成员的名称用户要导出时要导出的内容:

The only time you want to define __all__ in your package's __init__.py is to list the names of "exported" members that you want to export for when a user does:

from package import *

此文档记录在 6.4.1中.从包中导入*

注意:如果您在程序包中定义__all__,则默认行为如下(来自文档 ):

Note: If you don't define an __all__ in your package then the default behaviour is as follows (from the documentation):

如果未定义__all__,则来自sound.effects import的语句* 不会从sound.effects包中导入所有子模块到 当前名称空间;它仅确保包sound.effects具有 已导入(可能在其中运行任何初始化代码 __init__.py ),然后导入包中定义的任何名称.这包括任何已定义的名称(和明确的子模块 由__init__.py加载).它还包括程序包的任何子模块 由先前的import语句显式加载的文件.考虑 这段代码:

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

对此的天真"解释可以是:

A "naive" interpretation of this can be:

如果您未定义__all__from package import *将带入该软件包中的所有内容以及从

If you don't define __all__; a from package import * will bring in everything from that package and anything imported in that pacakge's __init__.py.

这篇关于为什么要在python包的__init__中使用__all__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆