Skip to content

Instantly share code, notes, and snippets.

@yantor3d
Created September 11, 2023 20:37
Show Gist options
  • Save yantor3d/eb2c34915612bc28b83ca9f144a5b5fb to your computer and use it in GitHub Desktop.
Save yantor3d/eb2c34915612bc28b83ca9f144a5b5fb to your computer and use it in GitHub Desktop.
A Python script to unload all modules within a package
"""Python utilies."""
import os
import sys
def unload(pkg):
"""Unload all imports from the given package.
Args:
pkg (module): Python module to unload.
"""
pkg_dir = os.path.abspath(os.path.dirname(pkg.__file__))
def _is_part_of_pkg(module_):
mod_path = getattr(module_, "__file__", os.sep)
mod_dir = os.path.abspath(os.path.dirname(mod_path))
return mod_dir.startswith(pkg_dir)
to_unload = [name for name, module in sys.modules.items() if _is_part_of_pkg(module)]
for name in to_unload:
sys.modules.pop(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment