How to have application-wide global objects
zarrg at hotmail.com
zarrg at hotmail.com
Thu Jul 13 12:01:54 EDT 2006
Sanjay wrote:
> Probably a newcomer question, but I could not find a solution.
>
> I am trying to have some singleton global objects like "database
> connection" or "session" shared application wide.
>
> Trying hard, I am not even being able to figure out how to create an
> object in one module and refer the same in another one. "import"
> created a new object, as I tried.
Try the "borg" pattern:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
It's very simple and does what you need. Don't be put off by comments
that "it's not a *real* singleton".
Or, use a module-level object, e.g.:
----db.py----
class db_conn:
def __init__(self, dbname, dbhost):
self.conn = whatever(dbname, dbhost)
conn = db_conn('mydb", "myhost")
----app.py----
import db
...
cur = db.conn.cursor()
cur.execute("select lkjlkj")
Repeated imports of db by various modules in an application
do *not* rerun the code in db.py .
-- George
More information about the Python-list
mailing list