0

I was going through the python 2.7 'modules' documentation to understand better how the import mechanism works in python.

Following is an extract that confuses me. Could someone help me understand what is written starting 'If __all__ is not defined...'

For example, the file sound/effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound package.

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from...import statement is executed. (This also works when all is defined.)

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practice in production code.

Tushar Vazirani
  • 1,011
  • 13
  • 14
  • 1
    Possible duplicate of [Can someone explain \_\_all\_\_ in Python?](https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python) –  May 30 '18 at 17:00
  • Thanks. Sorry for the inconvenience. Voting to close. – Tushar Vazirani Jun 08 '18 at 08:53

0 Answers0