Python docs: Importing everything from python package convention not clear

Viewed 42

The docs say:

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.

The first clause (before ';') says does not import, the second clause says then imports whatever names are defined. Isn't that a contradiction to the first clause? Logically, everything is imported eventually, so why this convolued wording?

2 Answers

The important distinction is "imports whatever names are defined in the package" vs "does not import all submodules".

Submodules aren't automatically names in the package __init__ module (unless explicitly imported to be).

IOW, with a package

foo/
  __init__.py
  baz.py

with foo/__init__.py containing

def bar():
   print("bar")

the statement

from foo import *

will only bring the function bar into scope (from foo/__init__.py), but not baz (a submodule in the foo package) into scope, unless it's a name in foo/__init__.py, á la

from . import baz

To refer to the sound/ hierarchy in the linked docs (in an abridged form, and assuming there is no code in those __init__.py files):

sound/
  __init__.py    # Initialize the sound package
  formats/       # Subpackage for file format conversions
    __init__.py
    wavread.py   # Read WAV files

this means that your application doing

from sound import *

will not put formats in the scope and

from sound.formats import *

won't give you wavread either.

If __all__ is not defined it will import every name from the module that does not start with an _.

def _private(): ...  # won't import

def public(): ...    # will import
Related