Created
November 6, 2025 20:08
-
-
Save hasansezertasan/e762570b2cae8f028c8d0ce78c3b9985 to your computer and use it in GitHub Desktop.
Detects if importing the given module causes any use of __import__() or importlib.import_module() at runtime.
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
| """ | |
| detector.py | |
| ------------------ | |
| Usage: | |
| python -m detector fastapi | |
| Detects if importing the given module causes any use of | |
| __import__() or importlib.import_module() at runtime. | |
| """ | |
| import sys | |
| import importlib | |
| import builtins | |
| import traceback | |
| def main(target_module: str): | |
| skip_modules = sorted(sys.stdlib_module_names) | |
| skip_modules.append(target_module) | |
| original_import = builtins.__import__ | |
| original_importlib_import = importlib.import_module | |
| found = [] | |
| def log_builtin_import(name, *args, **kwargs): | |
| if name not in skip_modules: | |
| info = f"__import__('{name}')" | |
| print(f"[Detected] {info}") | |
| traceback.print_stack(limit=3) | |
| found.append(info) | |
| return original_import(name, *args, **kwargs) | |
| def log_importlib_import(name, *args, **kwargs): | |
| if name not in skip_modules: | |
| info = f"importlib.import_module('{name}')" | |
| print(f"[Detected] {info}") | |
| traceback.print_stack(limit=3) | |
| found.append(info) | |
| return original_importlib_import(name, *args, **kwargs) | |
| # Patch | |
| builtins.__import__ = log_builtin_import | |
| importlib.import_module = log_importlib_import | |
| print(f"[INFO] Importing module '{target_module}' with dynamic import hooks enabled...\n") | |
| try: | |
| importlib.import_module(target_module) | |
| # exec(f"import {target_module}") | |
| except Exception as e: | |
| print(f"[ERROR] Importing {target_module} raised an exception: {e}") | |
| finally: | |
| # Restore originals | |
| builtins.__import__ = original_import | |
| importlib.import_module = original_importlib_import | |
| if not found: | |
| print(f"\nNo dynamic imports detected while importing '{target_module}'.") | |
| else: | |
| print(f"\nDetected {len(found)} dynamic imports while importing '{target_module}'.") | |
| if __name__ == "__main__": | |
| if len(sys.argv) < 2: | |
| print("Usage: python -m detector <module_name>") | |
| sys.exit(1) | |
| main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment