Home > Net >  import * modules clarification
import * modules clarification

Time:01-16

The Python Tutorial, mentions this following statement within the chapter 6. Modules.

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

The questions is, if there were no previous import statements

import sound.effects.echo
import sound.effects.surround

,would echo and surround be not imported? If yes, how does using the two above mentioned import statements exactly change the behaviour of import *?

CodePudding user response:

Dotted module names do not imply the existence of any attributes on a containing package, despite the identical syntax. The package sound does not necessarily have an attribute named effects, though the module name sound.effects refers to a module named effects contained in the package sound.

import sound.effects.echo does several things:

  1. Binds the package sound to the name sound in the current scope
  2. Binds the module sound.effects to an attribute named effects on the module sound.
  3. Binds the module sound.effects.echo to an attribute named echo on the module sound.effects.

The statement from sound.effects import * does the following:

  1. Imports the module sound.effects, but does not bind it to any name in the current scope
  2. For each module global defined in sound.effects.__all__, or all module globals not prefixed with _ if __all__ is not defined, define a new name in the global scope and bind that name to the correponding module global.

CodePudding user response:

This answers it nicely.

Basically, import * will import everything in the module, except any submodules.

Your code will import the main sound module, as well as the echo and surround submodules.

This is a good example.

  • Related