Import and Packaging Modules
pkgutil
Provides helpers for package discovery and loader-related operations. iter_modules enumerates discoverable modules at specified locations without importing each candidate. Walking packages recursively may import package initializers; results depend on finder support. The example restricts discovery to a temporary directory.
Formal Syntax & Structure
python syntaxpython
import pkgutilReturn Value
module
Module namespace available through import; import is a statement, not a value-returning expression.
Working Example
Example Snippetpython
from pkgutil import iter_modulesfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as d: (Path(d) / "demo.py").write_text("value = 1\n") print([m.name for m in iter_modules([d])])