Created
July 3, 2026 22:21
-
-
Save midhunkrishna/87d8e8b853688eb321a322de82292e34 to your computer and use it in GitHub Desktop.
reload a python file after making an edit without restarting the repl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 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) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where to place this?