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.

Did this help you? Tip $1 Tip $2 Tip $5

One Response to “Fuck the Python Borg, I like Singleton Better”

  1. EGG Says:

    I like more singletons, in Ruby just do this:

    require ‘singleton’

    class MiClase
    include Singleton
    end

    In spanish a little more about Singleton in Ruby

    http://www.lacaraoscura.com/2006/05/23/patrones-de-diseno-en-ruby-singleton/

    Salu2

Leave a Reply