Where to place __all__ in a Python file?
Asked Answered
G

2

9

I am wondering, what the standard placement in a Python file for __all__?

My assumption is directly below the import statements. However, I could not find this explicitly stated/asked anywhere. So, in general, where should one place __all__?

Where would it be put in the below example file?

#!/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

Thank you in advance!

Grith answered 8/1, 2020 at 2:21 Comment(0)
J
18

Per 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.

So if you're following PEP 8 strictly, you were close. In practice, it's not obeyed strictly. A ton of the Python "included batteries" modules define __all__ after the imports, so your approach is perfectly fine.

Jeri answered 8/1, 2020 at 2:25 Comment(0)
H
2

As mentioned 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:

Heimer answered 8/1, 2020 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.