TIL: How to configure the Python REPL

Published October 09, 2025

On the Python forums an idea to add import auto was suggested as a way to have lazy imports for standard library modules. While I don't think this is a good idea for something to incoroporate into the language I think it's a great idea to incorporate into the REPL (a REPL is the interactive shell where you can run Python commands.) TIL about the PYTHONSTARTUP environment variable that can be used to define a script that will arbitrarily run when the REPL launches. This can be used to handle common imports, aliases, and helper functions that you might want to have defined in every session of the REPL. I haven't set one up yet but I'm going to give some thought about what I want mine to do.

EDIT: I gave it some thought and decided on some things I always want to have available. This is what it looks like now:


# Be explicit about what is being run when the REPL starts
print(f"Executing {__file__} as the startup script.")

# List of packages to import directly
imports = [
    "re",
    "datetime",
    "sys",
    "os",
    "math",
    "collections",
]

# List of `from X import Y` for quicker access
imports_from = {
    "pprint": ["pp", "pformat"],
}

# Loop over the packages and import them
for package in imports:
    cmd = f"import {package}"
    print(cmd)
    exec(cmd, globals())


# Loop over the from import and import them
for package, modules in imports_from.items():
    cmd = f"from {package} import {', '.join(modules)}"
    print(cmd)
    exec(cmd, globals())

# Cleanup any variables that were used
del imports_from, imports, cmd

Source: Ned Batchelder


Previous: Random choice from Javascript array Next: More about itertools