Hemanth's Scribes

python

Python vs Ruby Singleton

Author Photo

Hemanth HM

I had dug a bit into Singleton Pattern in JavaScript lately and also was playing with some Python and Ruby Singleton Design pattern and astonishingly they are very simple and one can enjoy reading the code, as so little code helps one to implement this pattern.

First up is Python:

# python -m doctest singleton.py
class Singleton(object):
    """
    >>> single = Singleton()
    >>> single #doctest: +ELLIPSIS

    >>> one = Singleton()
    >>> one == single
    True
    """
    def __new__(cls, *args, **kargs):
        if not hasattr(cls, '_inst'):
            cls._inst = super(Singleton, cls).__new__(cls, *args, **kargs)
        return cls._inst

Ruby’s turn - yes Ruby has stdlib ‘singleton’, so all one needs to do is:

>> class Spinster
>>   include Singleton
>> end
=> Spinster
>> lady = Spinster.new
NoMethodError: private method `new' called for Spinster:Class
    from (irb):14
>> lady = Spinster.instance
=> #<Spinster:0x...>

Hope you had fun, happy hacking!

Further reading:

#python#ruby#patterns