Created
September 11, 2023 20:37
-
-
Save yantor3d/eb2c34915612bc28b83ca9f144a5b5fb to your computer and use it in GitHub Desktop.
A Python script to unload all modules within a package
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
"""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