Importing modules with arguments

Charles Smith charles at sollum.tech
Fri Jul 30 12:55:05 EDT 2021


I have found myself wanting to import module and provide arguments to them. There's two main reason I could think of for this. First is to prevent a circular import, though most of circular imports can be prevented by changing the design. The second reason is to invert dependencies between two modules. It occurred to me when using libraries like FastAPI or Flask that it would be nicer to use and leaner if instead of:
1. Import FastAPI Router or FastAPI object directly
2. Create a Router
3. Use the route decorators

We could simply import a module with importlib and provide the router itself. You can then keep all the FastAPI related code inside its module and only have clean list of endpoints. Now this is actually doable right now, here's the snippet: https://gist.github.com/BinarSkugga/c281cbbe36e7f11bc0fd143ea1bb4dd4

Disclaimer: I have no idea what are the implication of this but I'd like to have it as a feature instead of this hack.


More information about the Python-list mailing list