Multiple modules with database access + general app design?

Daniel Dittmar daniel.dittmar at sap.corp
Thu Jan 19 12:08:54 EST 2006


Robin Haswell wrote:
> Ah I see.. sounds interesting. Is it possible to make any module variable
> local to a thread, if set within the current thread? 

Not directly. The following class tries to simulate it (only in Python 2.4):

import threading

class ThreadLocalObject (threading.local):
     def setObject (self, object):
         setattr (self, 'object', object)

     def clearObject (self):
         setattr (self, 'object', None)

     def __getattr__ (self, name):
         object = threading.local.__getattribute__ (self, 'object')
         return getattr (object, name)

You use it as:

in some module x:

db = ThreadLocalObject ()

in some module that create the database connection:

import x

def createConnection ()
     localdb = ...connect (...)
     x.db.setObject (localdb)

in some module that uses the databasse connection:

import x

def bar ():
     cursor = x.db.cursor ()

The trick is:
- every attribute of a threading.local is thread local (see doc of 
module threading)
- when accessing an attribute of object x.db, the method __getattr__ 
will first retrieve the thread local database connection and then access 
the specific attribute of the database connection. Thus it looks as if 
x.db is itself a database connection object.

That way, only the setting of the db variable would have to be changed.

I'm not exactly recommneding this, as it seems very error prone to me. 
It's easy to overwrite the variable holding the cursors with an actual 
cursor object.

Daniel



More information about the Python-list mailing list