While developing in Flask, I would like to put all of my models, controllers,... in their own, separate file. That way, I don't have to look for any controller, model in a large file; it keeps everything clean. It could look as follows:
/controllers
__init__.py
login.py
logout.py
profile.py
All these files have (almost) the same dependencies. I don't want to put all the dependencies in each file over and over again. One solution I've come up with is to use a depencies.py
file, which imports all the dependencies, which I then include in each seperate file.
/controllers
__init__.py
dependencies.py (all the imports)
login.py (import dependencies.py)
logout.py (import dependencies.py)
profile.py (import dependencies.py)
However, this is not a very elegant solution. I wonder whether it's possible to do something like an __init__.py
which has the dependencies on top, and then 'includes' the separate files, and that everything is run that way, so that you don't actually need to include the common dependencies in each file.
Example of what I would like to do (does not work):
#common dependencies
from app import mail
from flask import session
...
#actual models (which depend on these dependencies)
from user import User
from code import Code
from role import Role
Import only the necessary dependancies in each or your files. If profile
only needs flask
, import only that in the file. If login.py
needs flask
and app
, import both in that file. Unless a 3rd party module is actually used in __init__.py
's code, you don't need to import it there. Depending on how you eventually use your package you can set the __all__
list with your modules in __init__.py
.
References:
Importing only ever loads a module once. Any imports after that simply add it to the current namespace.
- another answer
For efficiency reasons, each module is only imported once per interpreter session.
- python docs
__all__
explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With