best way to share an instance of a class among modules?

CM cmpython at
Wed Feb 6 23:41:43 CET 2013

On Feb 6, 12:04 am, Terry Reedy <tjre... at> wrote:
> On 2/5/2013 11:40 PM, CM wrote:
> > I have recently moved all my SQLite3 database-related functions into a
> > class, DatabaseAccess, that lives in a "utilities" module.  When the
> > application loads, the namespace of the instance of the class is
> > populated with two different cursors for two different databases the
> > whole application needs to use.  One of those cursors always refers to
> > a connection to the same database, but the other cursor can change
> > which database it refers to; in this regard, the namespace of the
> > DatabaseAccess class instance holds a "state" (which is which database
> > the one cursor currently refers to)
> > I have a number of modules that all need to use those two cursors.
> > However, if I import the utilities module and create a new instance of
> > the DatabasesAccess() in each of all the various modules, obviously
> > each new instance doesn't have the same namespace as the first
> > instance, and so doesn't have the *same* two cursors.
> > I can think of a few ways to pass the DatabaseAcess instance around to
> > the various modules, but all of them seem like repeating myself and
> > clunky.  What's the "best" (most Pythonic, simplest) way for a number
> > of modules to all share the same instance of my DatabaseAccess class?
> Attach the instance of the class to the utilities module that clients
> import. It does not matter if the code is in the utilities module itself
> or in one of the importing modules (possibly the first).
> # in module
> shared_cursor =
> # in importer
> import utilities
> utilities.shared_cursor = DatabaseAccess(args)
> Module attributes are mutable and can be set from elsewhere.
> --
> Terry Jan Reedy

Thank you.  But, I'm sorry, I'm not following this enough to get it to
work.  Shouldn't it be a little more like this:

# in utilities module
shared_cursor =  DatabaseAccess_instance  #but how? see my question

# in importer
import utilities
self.shared_cursor = utilities.shared_cursor  ("self" is here to make
cursor available to all functions in importer

My only problem, then, is I create the shared_cursor from within a
function within the instance of DatabaseAccess().  How then do I pass
it from within the function's namespace to the module's namespace so
that I can do that first line?

More information about the Python-list mailing list