Skip to content

Instantly share code, notes, and snippets.

@midhunkrishna
Created July 3, 2026 22:21
Show Gist options
  • Select an option

  • Save midhunkrishna/87d8e8b853688eb321a322de82292e34 to your computer and use it in GitHub Desktop.

Select an option

Save midhunkrishna/87d8e8b853688eb321a322de82292e34 to your computer and use it in GitHub Desktop.
reload a python file after making an edit without restarting the repl
"""
Drop in REPL: `import reloader; reloader.interact()` at the bottom of a script.
Gives you tab completion, persistent history and reload() function
that re-execs the calling-scropt into the live REPL namespace
"""
import atexit
import code
import os
import readline
import rlcompleter
import sys
def interact(ns=None, histfile=None, banner=""):
if ns is None:
# the globals of whoever called uss, i.e the script's namespace
ns = sys._getframe(1).f_globals
# reload() re-execs the caller, which calls interact() again- bail out
if ns.get("_RELOADER_ACTIVE"):
return
ns["_RELOADER_ACTIVE"] = True
src_file = ns.get("__file__")
if histfile is None:
# per script history, eg: ~/.file.py.history
name = os.path.basename(src_file) if src_file else "repl"
histfile = os.path.expanduser(f"~/.{name}.history")
def reload():
"""re-exec the calling script into the REPL's namespace"""
with open(src_file) as f:
exec(compile(f.read(), src_file, "exec"), ns)
print(f"reloaded {src_file}")
ns["reload"] = reload
try:
readline.read_history_file(histfile)
except OSError:
pass
readline.set_history_length(1000)
atexit.register(readline.write_history_file, histfile)
readline.set_completer(rlcompleter.Completer(ns).complete)
if "libedit" in (readline.__doc__ or ""):
readline.parse_and_bind("bind ^I rl_complete") # macOS system libedit
else:
readline.parse_and_bind("tab: complete")
code.interact(local=ns, banner=banner)
@midhunkrishna

Copy link
Copy Markdown
Author

Where to place this?

mkdir -p "$(python3 -m site --user-site)"
cp reloader.py $(python3 -m site --user-site)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment