Fuck the Python Borg, I like Singleton Better

I'm looking for a sponsor, Häagen-Dazs wants a geek??

I’ve read in parts of the web (and on the Martinelli’s Python Cookbok) that it’s better to do the Borg pattern over singletons, they say something alongs the lines of:

“who cares about identity, care about shared state”

Coming from the Java world, I just can’t understand that, why waste memory and cpu to address objects that share a state when you can have a single object in memory.

If you’re looking on how to implement singleton in a simple manner with Python, do the following my friend:

class MyClass:
  __INSTANCE__ = None

  def __init__(self):
    #do whatever you need on your constructor
    pass

  @staticmethod
  def getInstance():
    if MyClass.__INSTANCE__ is None:
      MyClass.__INSTANCE__ = MyClass()
    return MyClass.__INSTANCE__

#Then use it.
theOne = MyClass.getInstance()

Done deal, now start trolling on why this code sucks so we can fix it.

One thought on “Fuck the Python Borg, I like Singleton Better

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.