suggestions for functional style (singleton pattern?)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Mar 1 10:55:45 EST 2015


Michael Torrie wrote:

> Is not "only one object is ever created from a given class" the same as
> "could not be [instantiated] more than once?"

Not really.

A class which you merely happen to only instantiate once is not a singleton
class. It's just a class that you instantiate N times, where so far N has
only equalled 1.

A singleton class on the other hand is a class where N *must* equal 1,
because the class itself enforces that rule.

More generally, N may equal some small value, e.g. a Boolean class might
have a fixed set of exactly 2 instances. Sometimes people try to invent
names like "doubleton" for these, but none of those names have really taken
off.

Python modules are an interesting case. Although we often call them
singletons, they're actually nothing like a singleton. Modules are
instances of ModuleType, and there is no upper limit to the number of
instances that can be created. It's not even true that Python enforces only
a single instance per module, there are ways to get around that (albeit
normally you don't want to get around it!). Here is just once way:


# Don't do this at home!
py> import sys
py> mysys = sys
py> del sys.modules['sys'], sys
py> import sys
py> sys is mysys
False


Nevertheless, modules can be used to implement similar semantics to those of
singleton classes, and in particular they provide the most important
features of singleton classes for free. But calling them singletons just
because they quack like singletons is a little weird. Next we'll be calling
the Borg pattern "singletons".




-- 
Steven




More information about the Python-list mailing list