Created
April 13, 2025 00:07
-
-
Save cgoldberg/c3d87aeb57b362ef2edac33ea07e0c5b to your computer and use it in GitHub Desktop.
Python - Find all modules in a package without importing the 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
#!/usr/bin/env python3 | |
# | |
# Find all modules in a package without importing the package. | |
# Returns a list of module names. | |
# This will work for a package installed in `site-packages` or read from source. | |
# | |
# Requires Python 3.9+ | |
import importlib.util | |
import os | |
import site | |
def get_modules(package_name): | |
try: | |
mod_paths = importlib.util.find_spec(package_name).submodule_search_locations | |
except AttributeError: | |
raise Exception("package not found") | |
modules = [package_name] | |
for mod_path in mod_paths: | |
path = mod_path if "site-packages" in mod_path else package_name | |
for dirpath, _, filenames in os.walk(path): | |
for filename in filenames: | |
if filename.endswith(".py") and not filename.startswith("__"): | |
module_name = ( | |
os.path.join(dirpath, filename) | |
.removeprefix(site.getsitepackages()[0]) | |
.removeprefix(os.sep) | |
.removesuffix(".py") | |
.replace(os.sep, ".") | |
) | |
modules.append(module_name) | |
return sorted(set(modules)) | |
if __name__ == "__main__": | |
# example usage: | |
modules = get_modules("requests") | |
for module in modules: | |
print(module) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment