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!
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.
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With