简体   繁体   中英

Cross module variable sharing without duplicating imports

I have a module models.py with some data logic:

db = PostgresqlDatabase(database='database', user='user')

# models logic

and flask app which actually interacts with database:

from models import db, User, ...

But I want to move initializing all setting from one config file in flask app:

So I could separate importing db from other stuff (I need this for access to module variable db in models ):

import models
from models import User, ...
app.config.from_object(os.environ['APP_SETTINGS'])
models.db = PostgresqlDatabase(database=app.config['db'],
                               user=app.config['db'])

and use further db as models.db

But seems it is kinda ugly. Duplicating imports, different usage of module stuff..

Is there any better way how to handle this situation?

I'd recommend 1 level of indirection, so that your code becomes like this:

import const
import runtime

def foo():
    runtime.db.execute("SELECT ... LIMIT ?", (..., const.MAX_ROWS))

You get:

  • clear separation of leaf module const
  • mocking and/or reloading is possible
  • uniform and concise access in all user modules

To get rich API on runtime , use the "replace module with object at import" trick ( see __getattr__ on a module )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM