Singleton classes (with no such thing as static variables)

Gregory Bond gnb at itga.com.au
Fri Jul 13 02:20:03 CEST 2001


Giles Constant <gilesc at hyperlink-interactive.co.uk> writes:

> (with respect to constant/variable data, I'm actually passing around a
> class which can provide database cursors from a single active connection,
> but I can do something with what you've pointed me at!)

Here's what I use for exactly this:

In module dbhandle:
-------
import Sybase

__the_db = None

def db():
    '''
    Create the singleton database handle if required and return it.
    '''
    global __the_db
    if __the_db is None:
        __the_db = Sybase.connect(<connect arguments...>)
    return __the_db
-------
In the client code
-------
from dbhandle import db

db().execute('use databasename')
cursor=db().cursor()
#..... etc
-------

which works well enough for our purposes.



More information about the Python-list mailing list