Is there a better way to dynamically load submodules?

Hi folks,

I’m developing a FastAPI application and would like to place a bunch of APIRouter instances in a directory. I don’t want to manually import each of the routers. I have found a way to make it dynamic, but it is a bit of an eyesore:

# routers/__init__.py
from importlib import import_module
import pkgutil
from pathlib import Path

from fastapi import APIRouter

routers: list[APIRouter] = []

for module in pkgutil.walk_packages([Path(__file__).absolute().parent]):
    routers.append(import_module(f".{module.name}", __package__).router)

This seems like a hack, and I doubt I will be able to understand what it does in 3 years. Is there a better way?

Thanks!

1 Like

Fully document your script via comments and or docstrings and you should have no problems.

For example, along with a detailed description of the functionality of the script, you may also add commentary regarding the reason for importing each library. Include anything that will help you when referencing your script at a later date.