Hemanth's Scribes

python

Python vs Ruby Singleton

Author Photo

Hemanth HM

Thumbnail

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
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.