From 0c054f79e305abb2a3a368809754d71697afb288 Mon Sep 17 00:00:00 2001 From: lonetwin Date: Tue, 9 Feb 2021 23:58:23 +0000 Subject: [PATCH] Exciting new command - reload ! reload command (default: \r ) - If argument is a module, simply call `importlib.reload()`. - If argument is not a module, try hard to re-execute the (presumably updated) source code in the namespace of the object, in effect reloading it. Would love to receive feedback on whether this works well or breaks stuff --- pythonrc.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/pythonrc.py b/pythonrc.py index 0bbf8cf..a9f3aa5 100755 --- a/pythonrc.py +++ b/pythonrc.py @@ -80,7 +80,7 @@ from itertools import chain from operator import attrgetter from tempfile import NamedTemporaryFile -from types import SimpleNamespace +from types import ModuleType, SimpleNamespace __version__ = "0.9.0" @@ -97,6 +97,7 @@ DOC_URL = "https://docs.python.org/{sys.version_info.major}/search.html?q={term}", HELP_CMD = r'\h', LIST_CMD = r'\l', + RELOAD_CMD = r'\r', AUTO_INDENT = True, # - Should we auto-indent by default VENV_RC = os.getenv("VENV_RC", ".venv_rc.py"), # - option to pass to the editor to open a file at a specific @@ -283,6 +284,7 @@ def __init__(self, *args, **kwargs): self.commands = { config.EDIT_CMD: self.process_edit_cmd, config.LIST_CMD: self.process_list_cmd, + config.RELOAD_CMD: self.process_reload_cmd, config.SH_EXEC: self.process_sh_cmd, config.HELP_CMD: self.process_help_cmd, config.TOGGLE_AUTO_INDENT_CMD: self.toggle_auto_indent @@ -701,6 +703,35 @@ def process_list_cmd(self, arg): for line_no, line in enumerate(src_lines, offset + 1): self.write(cyan(f"{line_no:03d}: {line}")) + @_doc_to_usage + def process_reload_cmd(self, arg): + """{config.RELOAD_CMD} - Reload object, if possible. + + - if argument is a module, simply call importlib.reload() for it. + + - if argument is not a module, try hard to re-execute the + (presumably updated) source code in the namespace of the object, + in effect reloading it. + + credit: inspired by the description at https://github.com/hoh/reloadr + """ + if not arg: + return self.writeline('reload command requires an ' + f'argument (eg: {config.RELOAD_CMD} foo)') + + try: + obj = self.lookup(arg) + if isinstance(obj, ModuleType): + self.locals[arg] = importlib.reload(obj) + else: + namespace = inspect.getmodule(obj) + exec(compile(inspect.getsource(obj), namespace.__file__, 'exec'), + namespace.__dict__, + self.locals) + except OSError as e: + self.writeline(e) + + def process_help_cmd(self, arg): if arg: if keyword.iskeyword(arg):