Python – The folder where modules are imported in Python

The folder where modules are imported in Python… here is a solution to the problem.

The folder where modules are imported in Python

Is it possible to get a list of modules from a folder/package in python and import them?

I would like to be able to do this from a function in the class so that the entire class can access them (probably through the __init__ method).

Any help would be appreciated.

Solution

See also modules document

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. It is up to the
package author to keep this list up-to-date when a new version of the
package is released. Package authors may also decide not to support
it, if they don’t see a use for importing * from their package. For
example, the file sounds/effects/__init__.py could contain the
following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound package.

Yes, you can find a way to do this by listing the directories for the files in the directory and importing them manually. But there is no built-in syntax to meet your requirements.

Related Problems and Solutions