global variables extended to other objects/modules

Robert Brewer fumanchu at amor.org
Fri Apr 16 19:52:49 EDT 2004


Kamil wrote:
> Actually I'm working on an web application based on
> mod_python...
> I need a link to the database that will be
> accessible from _every_ module and object that needs to
> use it.
>8
> The problem wouldn't be so big if I hadn't so many 
> attributes I need to pass to most of my objects, like
> request, session, configuration and other attribs that
> should be 'application-wide'
> It would be very bad to define in every object __init__
> which will have so many arguments.

Some options:

1. Create a single Request object which you pass around. When you create
the Request object, you give it hooks to those other items:

def handle_request():
    req = Request()
    req.session = current_session
    req.dblink = dblink

...my current Big Project, for example, has a UI argument which gets
created for each request. The UI object has a 'namespace' attribute,
which is bound to a Namespace object. The Namespace object has hooks to
OO->DB 'server' objects, which handle storage managers, which might be
database wrappers.

2. Create a global in controller.py. When mod_python loads a module, it
shares it among requests. So once you've declared the global, it should
be fine. You have to make sure you only run your initialization code
once.

3. Use singleton classes instead of module-level globals. Not much
different from #2. Probably cleaner, though, especially if you find out
later you need more than one after all. FWIW, I got bit by that recently
when I built a framework, then two very different apps on top of it.
Guess what happened to the framework globals when I first tried running
them simultaneously? ;) Now I use a Namespace object for each app.

4. Serialize the more static data, with pickle or some other method.
There are lots of ways to share state.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list