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:
Now the usage is simple:
and won't break in the case you identify above:
You can also inherit from
Foo
; the child class will also be aSingleton
.One issue to be aware if is that if you implement
Foo.__init__
, it will be called every timeFoo()
is called. If that is undesirable, move the initialisation to the constructor (i.e. implementFoo.__new__
instead, remembering to call thesuper
constructor too).