David
David

Reputation: 4873

Storing a unopened database connection in a Python variable

I'm having trouble coming up with how to search this, so if the answer already exists, please just point me in the right direction and I will gladly delete this.

I have this in my Python code

db = pg_driver.connect(user     = DB_NAME,
                       password = DB_WORD,
                       host     = DB_HOST,
                       port     = DB_PORT
)

That all works perfectly. I'm curious though if I could put that into a global file, and then, do something like this:

db = global.db
# OR something like this, where the () says to actually do the opening.
db = global.db()

Then, just the local db would have the open connection, but global.db would just hold how what I would normally put to open the DB. The idea is that instead of having four lines, I would just have one, and if I ever changed something about how I connect to my database, I could update everything at once, instead of having to update multiple things.

However, I don't want global.db to hold an ever open database connection, as that could lead to issues with updating. Furthermore, I could never use good practice of opening and closing a DB just when I need it. If I were to keep my code as shown, and call db.close() then global.db would also be closed, and rendered useless for any other uses in the script.

Ideally this would be done with a macro, but Python doesn't have those from what I understand.

Thanks.

Upvotes: 0

Views: 174

Answers (1)

chepner
chepner

Reputation: 531918

In global.py, create a partial object.

import functools
db = functools.partial(pg_driver.connect,
                       user=DB_NAME,
                       password=DB_WORD,
                       host=DB_HOST,
                       port=DB_PORT)

Then, db is a callable object that can be used like you want.

import global
db = global.db()

Upvotes: 1

Related Questions