The code module provides classes for building an interactive loop similar to Python's REPL. It helps internal tools, teaching, and local debugging, but it is not a safe executor for untrusted users.
Share a controlled namespace
from code import InteractiveConsole
namespace = {"tax_rate": 0.2}
console = InteractiveConsole(namespace)
more = console.push("total = 100 * (1 + tax_rate)")
assert more is False
assert namespace["total"] == 120.0
Recognize incomplete input
push() returns true when a statement needs more lines, as after for or def. interact() manages prompts and a complete session. Customize messages for context without suppressing exceptions needed for diagnosis.
Never mistake a REPL for a sandbox
Restricting the initial dictionary does not prevent imports, introspection, or access to process resources. Do not expose this console to the web or untrusted input. Keep debugging sessions local, temporary, and observable.
Keep learning
Continue with safe debugging with PDB. The official Python documentation, accessed July 22, 2026, covers InteractiveInterpreter, InteractiveConsole, and error customization.