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

Terry Reedy tjreedy at udel.edu
Wed Feb 6 06:04:05 CET 2013


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




More information about the Python-list mailing list