Keeping a database connection with a Singleton?

Peter Otten __peter__ at web.de
Wed Sep 19 09:45:45 EDT 2007


exhuma.twn wrote:

> I remember reading about the Singleton pattern in python and how it's
> an unpythonic pattern and all. At the time I did not need the
> Singleton anyways, so I just glanced over the document.
> 
> But, setting this aside: I have an application where I have a
> connection to a database. At some point in the application I open up a
> new window. The new windows resides in a different module. So I have a
> directory structure like this:
> 
> - mainapp.py
> - newwindow.py
> 
> So I import "newwindow" in "mainapp"  so I can instantiate and display
> it. Meanwhile, the main-app has an open connection to the database.
> What's the cleanest way to hand this connection to the new window? I
> can see several possibilities:
> 
> 1) Simply pass the connection as paramtere to the constructor of new-
> window.
> 2) Use the "Singleton" deisign pattern to keep a reference to the
> connection
> 3) Open up a completely new connection to the database in the new
> window.
> 
> Now, option 1) is clearly the easiest to implement, however, I somehow
> tend to use option 2 (the singleton) as it's more flexible. Option 3
> looks ugly to me.
> 
> This is a stuation I run into many times. And I am always faced with
> the same choice. And I never know which one to chose. And now that I
> am getting more and more comfortable with the basics of python, I
> would like to know if I am missing something more "pythonic".
> 
> So, what would you recommend?

Passing the connection as a parameter is the best approach because it
keeps the dependencies explicit. Also, it allows you to switch between
singleton and one connection per window without ever touching the newwindow
module.

By the way, there is a pythonic (near) singleton: the module. So if you go
with option 2, just move the connection setup into a separate module that
you can import into client code.

Peter



More information about the Python-list mailing list