Import and Packaging Modules
runpy
Locates and executes trusted modules or scripts in a fresh namespace and returns their globals. Unlike static compilation, execution can change process state, import modules and perform side effects. It is not a sandbox. The example executes only a fixed, locally created script.
Formal Syntax & Structure
python syntaxpython
import runpyReturn Value
module
Module namespace available through import; import is a statement, not a value-returning expression.
Working Example
Example Snippetpython
import runpyfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as d: p = Path(d) / "demo.py" p.write_text("total = 2 + 3\n") print(runpy.run_path(str(p))["total"])