What do you call a class not intended to be instantiated

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Sep 27 10:20:17 CEST 2008

Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote:
> > An ordinary singleton is instantiating the class multiple times
> > yet returning the same instance object; a class singleton is
> > simply using the class directly (like a module).

Where is this "class singleton" terminology from? It seems redundant
to me. It also doesn't seem to have anything to do with what
"singleton" means as a pattern; "using a class" is simply using a

> Since I now no longer think I need such a beast

That's a relief :-)

> I'd like to be able to call [a class] as if it were a function.
> Normally calling a class object returns an instance -- I wish to
> return something else.

In that case, you *don't* want a class at all; the entire point of a
class is to define behaviour for instances.

Instead, you want to define a class whose *instances* are callable, by
defining the '__call__' method to do whatever it is you want.

> This seems to works:
> >>> class ClassSingleton(object):
> ...     thing = (0, 1, 2)
> ...     def __new__(cls, *args):
> ...             return len(args+cls.thing)
> ...
> >>> ClassSingleton(1, 2, 4, 8, 16)
> 8

Horribly obfuscatory. Calling a class should return a new instance of
the class or something like it.

Instead, define it so the user instantiates the class by calling the
class, and *then* calls that non-class object, and so shouldn't expect
to get a new instance back:

    >>> class CallableAppendor(object):
    ...     thing = (0, 1, 2)
    ...     def __call__(self, *args):
    ...         return len(args + self.thing)
    >>> appendor = CallableAppendor()
    >>> appendor(1, 2, 4, 8, 16)

 \         “Pleasure's a sin, and sometimes sin's a pleasure.” —“Lord” |
  `\                              George Gordon Noel Byron, _Don Juan_ |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list