What do you call a class not intended to be instantiated

Aahz aahz at pythoncraft.com
Sat Sep 27 10:00:37 EDT 2008


In article <8763oiuhj2.fsf at benfinney.id.au>,
Ben Finney  <bignose+hates-spam at benfinney.id.au> wrote:
>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
>class.

I don't remember where I picked it up, probably here some years ago.
The point of the terminology is to distinguish how the class is *used*,
in precise parallel with "module singleton".

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

Absolutely agreed with your first clause, disagreed about the second
clause.  As I said earlier, the main point of a class singleton is to get
the effect of a module singleton without the need to create another file
on disk.  In that case there is no instance and therefore the point of
the class is no longer to define behavior for instances.

But you can't call a module, and classes have well-defined behavior for
calling them, so you shouldn't try to pervert a class singleton by
defining behavior for calling them.  In fact, I would recommend creating
an __init__() method that raises NotImplementedError precisely to prevent
this usage (or have a __new__() method that returns None, but I generally
prefer to recommend practices that work with classic classes).

One cute reason to prefer class singletons to module singletons is that
subclassing works well for creating multiple singletons.  But really,
the main reason I use class singletons is that they are the absolute
simplest way to get attribute access:

class Foo: pass
Foo.bar = 'xyz'
if data == Foo.bar:
    print "!"

Once it gets much more complicated than that, I prefer to use a smarter
object.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach



More information about the Python-list mailing list