It is recommended to not to use import *
in Python.
Can anyone please share the reason for that, so that I can avoid it doing next time?
As suggested in the docs, you should (almost) never use import *
in production code.
While importing *
from a module is bad, importing * from a package is probably even worse.
By default, from package import *
imports whatever names are defined by the package's __init__.py
, including any submodules of the package that were loaded by previous import
statements.
If a package’s __init__.py
code defines a list named __all__
, it is taken to be the list of submodule names that should be imported when from package import *
is encountered.
Now consider this example (assuming there's no __all__
defined in sound/effects/__init__.py
):
# anywhere in the code before import *
import sound.effects.echo
import sound.effects.surround
# in your module
from sound.effects import *
The last statement will import the echo
and surround
modules into the current namespace (possibly overriding previous definitions) because they are defined in the sound.effects
package when the import
statement is executed.