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
Is this a reasonable way to go about making a class singular?