__all__ 放在 Python 文件的什么地方?

Where to place __all__ in a Python file?

我想知道 __all__ 在 Python 文件中的标准位置是什么?

我的假设就在导入语句的正下方。但是,我无法在任何地方明确地 stated/asked 找到它。那么,一般来说,一个地方应该放在哪里__all__?

它会放在下面的示例文件中的什么地方?

#!/usr/bin/env python3

"""Where to put __all__."""

from time import time

# I think it should go here: __all__ = ["Hello"]

SOME_GLOBAL = 0.0


class Hello:
    def __init__(self):
        pass


if __name__ == "__main__":
    pass

提前致谢!

根据 PEP 8:

Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports.

因此,如果您严格遵守 PEP 8,那么您就很接近了。实际上,不是严格遵守。 Python "included batteries" 模块的 ton 在导入后定义 __all__,所以你的方法非常好。

如前所述here

Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings: