为什么要在python包的

编程入门 行业动态 更新时间:2024-10-24 16:22:35
本文介绍了为什么要在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在名称空间中,但A1和b不在名称空间中.为什么我必须定义__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包的

本文发布于:2023-11-14 15:26:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587829.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要在   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!