[CentralOH] Another Revision of Singleton

Eric Floehr eric at intellovations.com
Mon Mar 18 12:13:27 CET 2013


John,

In most cases where you think you need a Singleton design pattern, what you
are really looking for is shared state. It doesn't matter how many class
instances you have, so long as each of those instances share state.

The problem many people have coming to Python from say C++, Java, C# and
other class-oriented languages is that in those languages you can't easily
separate the class instance from its state. In Python, being *object*
oriented and not *class* oriented, it's easy. Another thing that tripped me
up, coming from Java, is thinking of a module as just a namespace and not
as an object as well.

With that said, there are two alternatives to the Singleton object that may
work better for you in Python than the implementation you'd
found/developed. At the very least, understanding them will help you
understand Python a little more.

The first is the multi-instance/shared-state pattern, which Alex Martelli
calls the "Borg Pattern". It's called the Borg pattern for obvious
reasons... like the Borg, there are many instances but all share the same
state :-). Alex's "Five Easy Pieces" post is a must read:
http://www.aleax.it/5ep.html

The second is that like everything in Python, a module is an object, not
just a namespace. In fact, a module can be thought of as a singleton... it
can have global state, has only once instance, and is an object. Here is a
stackoverflow explanation... there is probably a better description
somewhere but I can't find it in my bookmarks right now:
http://stackoverflow.com/questions/10936709/why-does-a-python-module-act-like-a-singleton

BUT...

I would take a step back even further and ask yourself if you really even
need a singleton. In most cases, you really don't, and you can make your
program better by eliminating them. Google even wrote a singleton detector
for its Java code:
http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

I can't tell you if your design would be better without a singleton without
knowing more about the use case. But at least read up on the Borg pattern
and on modules as singletons and you will at least have a better
understanding of Python.

Cheers,
Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20130318/68f02eac/attachment.html>


More information about the CentralOH mailing list