Split a large python file into a module with shared dependencies

When developing in Flask, I would like to put all my models, controllers ... in their own separate file. Thus, I do not need to look for any controller, model in a large file; he keeps everything clean. It might look like this:

/controllers __init__.py login.py logout.py profile.py 

All of these files have (almost) the same dependencies. I do not want to add all the dependencies to each file again and again. One solution I came up with is to use the depencies.py file, which imports all the dependencies, which I then include in each individual 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 if it is possible to do something like __init__.py , which has dependencies on top and then β€œincludes” individual files and that everything is done in this way, so that you actually do not need to include common dependencies in each file.

An 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 
+5
source share
1 answer

Import files individually

Import only the necessary dependencies in each or your files. If profile needed only by flask , import only this into the file. If login.py requires flask and app , import both into this file. If the __init__.py code does not actually use a third-party 3 rd module, you do not need to import it there. Depending on how you end up using your package, you can set the __all__ list with your modules in __init__.py .

Literature:

  • Import only ever loads a module once. Any import after that just adds it to the current namespace.
    - another answer

  • For efficiency reasons, each module is imported only once per interpreter session.
    - python docs

  • __all__ explanation

+1
source

All Articles