P
P
PyLearner2018-05-23 20:45:10
Python
PyLearner, 2018-05-23 20:45:10

Why can't you import via import *?

Documentation https://docs.python.org/3/tutorial/modules.html#pa...

Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package's __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

What's not clear:
This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

1) Why can it take a long time ? What can be in a package besides subpackages and modules? Why can't python itself read the names of the folders in the package and check for the presence of modules in them?
importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

2) From the fact that I myself enter the folder names in __init__.py __all__, and not the python itself identifies them according to a simple algorithm (folder = package, file .py = module), may there be any side effects? Which?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question