2

I have a database class in my module, db.py that I can only call once, my design goal is to have one single database object and have that be used across all other modules. So db has the layout

#db.py
Class DatabaseManager

    def __init__():
        # initialize engine and database

db = DatabaseManager()

The problem is across multiple imports db is reinitialized each time, what I want to be able to do is something along the lines of:

# polygon.py
from db import db        

class Polygon:

    def something(self):
        db.commitChange(...)

# main.py

class GUIWindow:

    def something(self):
        db.getJSON(...)

How can I create one object for the entire program, and have all other modules importing db use that one object? I was under the impression db would not be reinitialized, but I am receiving the engine initialization output twice, here's an example and my output

# db.py
class DatabaseManager(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        print "hi"

db = DatabaseManager()

# polygon.py
from db import db

# main.py
from db import db

output:

hi
hi
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

0 Answers0