Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion pythonrc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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} <object> - 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):
Expand Down