Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split large python file into module with common dependencies

Tags:

python

module

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__.pywhich 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
like image 212
Ben Avatar asked Nov 10 '22 15:11

Ben


1 Answers

File specific imports

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:

  1. Importing only ever loads a module once. Any imports after that simply add it to the current namespace.
    - another answer

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

  3. __all__ explanation

like image 61
tmthydvnprt Avatar answered Nov 14 '22 21:11

tmthydvnprt