"Frans Englich" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
On Monday 17 January 2005 20:03, John Roth wrote:"Frans Englich" <[EMAIL PROTECTED]> wrote in message
<snip>
In other words, you're trying to create a singleton. In general, singletons are frowned on these days for a number of reasons, not least because of the difficulty of testing them.
Then I have some vague, general questions which perhaps someone can reason
from: what is then the preferred methods for solving problems which requires
Singletons? Is it only frowned upon in Python code?
I don't know of any generic methods that will work in all cases _and_ are easy to apply. There are really two issues: testing and abuse of the pattern.
There really are some places where you want a single instance of something that is globally visible. Things that leap immediately to mind include the connection to a data base and a logger facility.
However, in a lot of cases, you find singletons used as an "object oriented" substitute for a global variable, which stinks just as badly as a global would. Since Python is a multi-paradigm language, just put in a global at the module level. It's clearer. Otherwise redesign.
There are several ways of getting around the testing difficulty. One is the "toolbox" pattern that appears in a number of places. The idea there is to have a single object that proxies all of the singletons so that they can be replace by testing versions at initialization time.
A neater and more modern method is to use an IOC (Inversion of Control) container, or at least the pattern involved. All IOC containers I'm aware of support singletons and make testing them almost trivially easy.
A third way is to simply take advantage of Python's dynamic nature and have your tests stuff the testing instance into the class object before the first call. This is an ad-hoc variation on the IOC principle.
HTH
John Roth
Cheers,
Frans
-- http://mail.python.org/mailman/listinfo/python-list