Created
April 10, 2023 21:18
-
-
Save kurtbrose/d41d8c6e33be158b713a90641b1cf191 to your computer and use it in GitHub Desktop.
Helper to recursively import all .py files on disk. This ensures that all side effects from importing a module "trigger". (For example, registering a model with the ORM, or adding routes.) Call it with the name of a top-level module within the directory.
This file contains 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
import re | |
import importlib | |
from pathlib import Path | |
def import_all(module_name: str, ignore: str = None) -> None: | |
""" | |
Helper to recursively import all .py files on disk. | |
This ensures that all side effects from importing a module "trigger". | |
(For example, registering a model with the ORM, or adding routes.) | |
Call it with the name of a top-level module within the directory. | |
""" | |
module = importlib.import_module(module_name) | |
module_dir = Path(module.__file__).parent | |
package = module.__package__ | |
ignore_pattern = re.compile(ignore) if ignore else None | |
def import_recursively(path, parent_package): | |
for file in path.iterdir(): | |
if file.is_dir() and (file / '__init__.py').is_file(): | |
import_recursively(file, f"{parent_package}.{file.name}") | |
elif file.suffix == '.py': | |
if file.stem == '__init__': | |
continue | |
module_name = f"{parent_package}.{file.stem}" | |
if ignore_pattern and ignore_pattern.match(module_name): | |
continue | |
importlib.import_module(module_name) | |
import_recursively(module_dir, package) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment