Brain Dead Singleton

Kamilche klachemin at home.com
Fri Jun 4 17:33:52 EDT 2004


I looked on this newsgroup, and saw all the problems with making a
Singleton class with Python.

I don't really care about 'returning the single shared instance' in
the constructor and all, I just want to avoid being inefficient... so
I implemented this (code fragment follows):

class Whatever:
    _singleton = 0
    def __init__(self):
        self.__class__._singleton += 1
        if self.__class__._singleton > 1:
            raise Exception("Singleton!")

There. I've got it trussed up to where I can't create more than one
without raising an exception, which works good enough for my purposes.

--Kamilche



More information about the Python-list mailing list