Abhishek Bhatia
Abhishek Bhatia

Reputation: 9816

how import * and __all__ work with submodules imports

The tutorial (4th paragraph, https://docs.python.org/3/tutorial/modules.html#importing-from-a-package) mentions :

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

Doubts:

  1. In the first statement, which previous import statements is it referring to?
  2. I cannot understand the statements and the example. To from sound.effects import * should not import anything unless defined in __all__ of __init__.py in the package.

Upvotes: 2

Views: 558

Answers (1)

Yibo
Yibo

Reputation: 11

  1. previous import statements refers to:

    import sound.effects.echo
    import sound.effects.surround
    
  2. According to CPython 3.6, from sound.effects import * only import submodules loaded in __init__.py (by defining __all__). That means you cannot use symbols in echo and surround when __all__ isn't defined.

Otherwise,

It also includes any submodules of the package that were explicitly loaded by previous import statements.

only works when __all__ defined in sound.effects's __init__.py like __all__ = ["echo", "surround", "reverse"].

Upvotes: 1

Related Questions