Programmatic importing

suggest change
import importlib
random = importlib.import_module("random")

The importlib.import_module() function will also import the submodule of a package directly:

collections_abc = importlib.import_module("collections.abc")

The old imp module has been removed. Use importlib.import_module() for ordinary dynamic imports, or the lower-level importlib.util APIs when loading from a specific file path.

Avoid calling __import__() directly. Its handling of package context and fromlist is easy to get wrong, while importlib.import_module() provides the intended high-level interface.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents