Python – Is it reasonable to use a decorator to instantiate a singleton in Python

pythonsingleton

Suppose I have a class like this:

class Foo(object):
    # some code here

As it happens, Foo is a singleton. There are numerous ways to write singletons in Python, but most of them don't really feel very Pythonic to me. If someone else has a particularly strong reason for instantiating or subclassing my class, I see no reason to go out of my way to make things unreasonably difficult for them (beyond a minimal "this is not part of the public API and might break everything" hint).

So I hit upon this idea:

def singleton(cls):
    return cls()

@singleton
class foo_instance(object):  # note lower case
    # some code here

I had to write singleton() myself because operator.call() isn't a thing for some strange reason.

Obviously, you can still just do type(foo_instance) and instantiate by hand, but the lack of a publicly visible class makes it obvious (to me) that you're not really supposed to do that (in much the same way as you're not supposed to mess around with type(enum.Enum) in 3.4+), and I think it looks cleaner than an underscore-prefixed "private" class such as class _Foo.

Is this a reasonable way to go about making a class singular?

Best Answer

I think the simplest, most Pythonic way to implement a singleton class is with inheritance:

class Singleton(object):

    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]


class Foo(Singleton):  # Foo 'is a' Singleton
    pass

Now the usage is simple:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True

and won't break in the case you identify above:

>>> foo3 = type(foo1)()
>>> foo1 is foo3
True

You can also inherit from Foo; the child class will also be a Singleton.

One issue to be aware if is that if you implement Foo.__init__, it will be called every time Foo() is called. If that is undesirable, move the initialisation to the constructor (i.e. implement Foo.__new__ instead, remembering to call the super constructor too).

Related Topic