1

I'm writing some util modules in Python3.10 and want that all function or class defined in
leaf node .py files can be import easily. Consider the following file sturctures:

A0
├─ B0
│    ├─ __init__.py
│    └─ b0.py
├─ B1
│    ├─ __init__.py
│    └─ b1.py
└─ __init__.py

Where b0.py is difined as:

# __all__ = ['func_b0']
def func_b0():...
def _func_b0():...
def __func_b0():...

If I write from .b0 import * into A0/B0/__init__.py, then I can use from A0.B0 import func_b0 in external file to use my custom function func_b0 easily, instead of use from A0.B0.b0 import func_b0.

My question is, need I add such as __all__ = ['func_b0'] into A0/B0/b0.py to control A0/B0/__init__.py's import * behavior? If I use private methods, i.e., underline or double underline, I can also control the import * behavior.

In my opinion, using private methods is a better way to control import * behavior, since only one change is required during maintenance. However, the former __all__=[...] method needs to maintain an additional list.

So, is __all__ not designed to be used here? Is there any PEP to discuss this problem (i.e., maybe import alias)?

Little Train
  • 707
  • 2
  • 11
  • 1
    you dont need to use `__all__` in `b0.py` file, just use it in `__init__.py` file and define wh ich method you want let the user access through `from A0.B0 import <*/some methods>` method . if user import without this from .py file directly like `from A0.BO.b0 import *` and you dont want to expose the private methods in this manner then you need to use `__all__` in the `.py` file – sahasrara62 Jun 15 '22 at 16:49
  • 1
    https://peps.python.org/pep-0008/#global-variable-names suggests a semantic distinction between `__all__` as meaning _"make these vars available via `import *`"_ and underscore-prefix meaning _"private var - avoid using as a 3rd party"_. In practice they probably usually coincide completely though. See comments here https://stackoverflow.com/questions/44834/what-does-all-mean-in-python – Anentropic Jun 15 '22 at 16:51

0 Answers0