Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place __all__ in a Python file?

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!

like image 632
Intrastellar Explorer Avatar asked Jan 08 '20 02:01

Intrastellar Explorer


People also ask

What does __ all __ mean in Python?

In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.

What is __ main __ file in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is __ PATH __ in Python?

Packages in Multiple Directories. Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed.

How do I import all files into Python?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.


2 Answers

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.

like image 151
ShadowRanger Avatar answered Sep 26 '22 16:09

ShadowRanger


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:

like image 21
U12-Forward Avatar answered Sep 26 '22 16:09

U12-Forward