[mod_python] Problem keeping persistent object in memory (global)

Graham Dumpleton grahamd at dscpl.com.au
Mon Jun 6 18:08:02 EDT 2005

On 07/06/2005, at 3:02 AM, Huzaifa Tapal wrote:

> One option that I use is to create a singleton in the module that I 
> want to be global at the first import of that module.  So lets take 
> your mySitePool module for example:
> class mySitePool:
>    def __init__(self):
>          ' suite
> ....
> global mysitepool
> mysitepool = mySitePool()

Using singleton approach as described will help, now for some really 
stuff in case later on you find other strange problems.

First is that if auto reloading of modules is on and the singleton is 
in a module which at any time might get reloaded because the file is 
the act of reloading will replace the singleton object, resetting it in 

This means that the previously created pool object will become 
and potentially resources it uses in the way of database connections 
not get shutdown properly if that required an explicit step not 
performed by
normal Python object deletion.

At the same time, a new pool object will be created and perhaps another 
of database connections. If old ones aren't cleaned up in the 
pool and new ones are created due to reloads, you might end up with too 
connections and not be able to create any more.

To make the code durable and resistant to reloads, intended or not, it 
useful to write code as:

if not globals().has_attr("mysitepool"):
   mysitepool = mySitePool()

What happens is that reload occurs on top of the existing module. By 
if the pool object already exists in globals, you simply avoid creating 
it a
second time.

Also note that there are some threading issues in mod_python as well, 
if you don't do this fiddle but module reloading is turned off, you can 
have a problem. This is because the threading issues can result in a 
being loaded twice by mistake, as if a reload had occurred.

For this, see patches at:



More information about the Mod_python mailing list