3

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?

7
  • 1
  • 1
    It's not reasonable to have singletons; regardless of the language or implementation.
    – DeadMG
    Mar 22 '15 at 12:07
  • @DeadMG: In Python, modules basically are singletons. They're first class objects.
    – Kevin
    Mar 22 '15 at 13:32
  • @Kevin Something only ever having one instance does not make it a singleton
    – Caleth
    Oct 5 '17 at 8:35
  • @Caleth: That's really interesting, I've never heard a definition of "singleton" other than "something with only one instance." Can you show me the definition you're working with, and where you read it?
    – Kevin
    Oct 5 '17 at 17:02
1

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).

1

Yes! It is absolutely reasonable... (I'd think)

I have "invented" (I should probably say "re-invented") it myself some long time ago, and still use it where needed. Here, "where needed" usually means "where it makes the intention clearer" and not "where I want to make sure nobody tricks their way to a second instance of that class".

I actually find the solution provided by @jonrsharpe not to be very Pythonic. It's a nice trick for sure! Even if you don't want to do it via inheritance but via a decorator, the general idea can be applied. But a constructor that returns an existing instance seems not Pythonic to me at all.

So, yes, simply hiding the class behind the sole instance does all that's intended. The fact that type(foo_instance)() will create a new instance does not detract from it. If one was bound to do similar things with other Python code, it was trivially simple to do so. Otherwise Python would also need to forbid external access to underscore methods, etc. So, it boils down to "we are all consenting adults here".

Note: I know this question is rather old, but I just found it when I was looking for a better (more Pythonic?) way to achieve the same out of curiosity. But the alternatives (even if they are clever and working well), don't seem to be any better. Thus, the simple design is probably best ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.