Multiple modules with database access + general app design?

Paul McGuire ptmcg at
Thu Jan 19 07:23:12 EST 2006

"Robin Haswell" <rob at> wrote in message
news:pan.2006. at
> Hey people
> I'm an experience PHP programmer who's been writing python for a couple of
> weeks now. I'm writing quite a large application which I've decided to
> break down in to lots of modules (replacement for PHP's include()
> statement).
> My problem is, in PHP if you open a database connection it's always in
> scope for the duration of the script. Even if you use an abstraction layer
> ($db = DB::connect(...)) you can `global $db` and bring it in to scope,
> but in Python I'm having trouble keeping the the database in scope. At the
> moment I'm having to "push" the database into the module, but I'd prefer
> the module to bring the database connection in ("pull") from its parent.
> Eg:
> import modules
> = db.cursor()
> Can anyone recommend any "cleaner" solutions to all of this?

Um, I think your Python solution *is* moving in a cleaner direction than
simple sharing of a global $db variable.  Why make the Bar class have to
know where to get a db cursor from?  What do you do if your program extends
to having multiple Bar() objects working with different cursors into the db?

The unnatural part of this (and hopefully, the part that you feel is
"unclean") is that you're trading one global for another.  By just setting to the db cursor, you force all Bar() instances to use that
same cursor.

Instead, make the database cursor part of Bar's constructor.  Now you can
externally create multiple db cursors, a Bar for each, and they all merrily
do their own separate, isolated processing, in blissful ignorance of each
other's db cursors (vs. colliding on the shared $db variable).

-- Paul

More information about the Python-list mailing list