Skip to content

Instantly share code, notes, and snippets.

@bisraelsen
Last active April 14, 2020 20:21
Show Gist options
  • Save bisraelsen/bd62c05d66d9ffd2f6b3e8e293a1bcfd to your computer and use it in GitHub Desktop.
Save bisraelsen/bd62c05d66d9ffd2f6b3e8e293a1bcfd to your computer and use it in GitHub Desktop.
Module to be used in the `~/.ipython/profile_default/startup/` folder. Automatically add function `clear()` to clear the workspace and reload modules. This is great for interactive development of code.
# from https://stackoverflow.com/questions/49299033/how-to-force-ipython-deep-reload
import sys
def _is_module_deletable(modname, modpath):
if modname.startswith('_cython_inline'):
# Don't return cached inline compiled .PYX files
return False
for path in [sys.prefix]:
if modpath.startswith(path):
return False
else:
return set(modname.split('.'))
def clear():
"""
Del user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
"""
log = []
for modname, module in list(sys.modules.items()):
modpath = getattr(module, '__file__', None)
if modpath is None:
# *module* is a C module that is statically linked into the
# interpreter. There is no way to know its path, so we
# choose to ignore it.
continue
if modname == 'reloader':
# skip this module
continue
modules_to_delete = _is_module_deletable(modname, modpath)
if modules_to_delete:
log.append(modname)
del sys.modules[modname]
print("Reloaded modules:\n\n%s" % ", ".join(log))
@bisraelsen
Copy link
Author

Later defined:

def test():
    clear()
    %run the_code.py

And then was able to just run test() to re-run the code after outside modifications.

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