Skip to content

Instantly share code, notes, and snippets.

@driazati
Created January 5, 2022 23:35
Show Gist options
  • Save driazati/f6d10554844c34671a3ff450a51f6b49 to your computer and use it in GitHub Desktop.
Save driazati/f6d10554844c34671a3ff450a51f6b49 to your computer and use it in GitHub Desktop.
check that all the folders in a Python module are reachable via a direct import statement
import textwrap
import importlib
from types import ModuleType
import tvm
from pathlib import Path
def has_init(p: Path) -> bool:
return len(list(p.glob("__init__.py"))) == 1
def module_folder(module: ModuleType) -> Path:
return Path(tvm.__file__).resolve().parent
def check_module(module_folder, prev=None):
if prev is None:
prev = []
if module_folder.name == "__pycache__":
return
# check module is importable
# if m.glob
# print(module_folder, has_init(module_folder))
path_items = prev + [module_folder.name]
path = ".".join(path_items)
try:
imported = importlib.import_module(path)
importable = True
except ModuleNotFoundError as e:
importable = False
reason = "module not found"
except ImportError as e:
importable = False
reason = str(e)
except Exception as e:
importable = False
reason = str(e)
if not importable:
print(f"Un-importable module path: {path}\n{textwrap.indent(reason, ' ')}")
for item in module_folder.glob("*"):
if item.is_dir():
check_module(item, path_items)
check_module(module_folder(tvm))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment