---
title: "Python vs Ruby Singleton"
description: "A comparison of Singleton design pattern implementation in Python vs Ruby. Practical notes and code examples on Python vs."
url: "https://h3manth.com/scribe/python-vs-ruby-singleton/"
canonical_url: "https://h3manth.com/scribe/python-vs-ruby-singleton/"
markdown_url: "https://h3manth.com/scribe/blog/python-vs-ruby-singleton.md"
publishDate: "2012-07-31T00:00:00.000Z"
author: "Hemanth HM"
category: "python"
tags: ["python","ruby","patterns"]
word_count: 156
reading_time_minutes: 1
x_markdown_tokens: 401
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Python vs Ruby Singleton

> A comparison of Singleton design pattern implementation in Python vs Ruby. Practical notes and code examples on Python vs.

I had dug a bit into [Singleton Pattern in JavaScript](http://h3manth.com/content/singleton-pattern-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
# 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:**

```ruby
>> 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:**

* [The Borg design pattern](http://code.activestate.com/recipes/66531/)
* [Ruby doc](http://ruby-doc.org/stdlib-1.9.3/libdoc/singleton/rdoc/Singleton.html)
