Why might we use from . import * in Python
Why might we use from . import * in Python
When you write from mypkg import *
, Python looks at the __all__
variable of the __init__.py
file of the package, which is believed to be filled with names of submodules. It then loads all the submodules listed in that variable into the local namespace. If __all__
does not exist, it loads instead all the symbols defined in the __init__.py
file (including submodules explicitely imported in that file, but not every submodule of the package). Reference.
You use from .
when you are in a submodule inside a package (intra-package reference). This refers to the package the submodule is in, whatever name it has. So from . import *
does exactly what is described above, but for the package the submodule is part of. Note that if the submodule is itself listed in the __all__
variable, then it will fail due to dependency loop.
Concerning your example, the module is itself the __init__.py
and also defines a __all__
variable, so it is lucky that Python doesnt crash on dependency loop. The line is useless anyway, as the local code doesnt make use of these modules.