Generic singleton

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 5 19:01:11 CET 2010


On Fri, 05 Mar 2010 11:57:13 -0500, Terry Reedy wrote:

> On 3/4/2010 10:32 PM, Steven D'Aprano wrote:
> 
>> Python does have it's own singletons, like None, True and False.
> 
> True and False are not singletons.

Duotons? Doubletons?

>>> t1 = bool(1)
>>> t2 = bool(1)
>>> t1 is t2
True
>>> t1 is t2 is bool("this is also true") is bool(['so', 'is', 'this'])
True

They're described as singletons in the PEP, so if you want to argue with 
Guido, go right ahead... *grin*

http://www.python.org/dev/peps/pep-0285/



>  > For some reason, they behave quite differently:
> 
> Because they are quite different.

Well, list("hello world") and list("goodbye now") are quite different 
too, but they behave very similarly.


>  > NoneType fails if you try to instantiate it again,
> 
> Because trying 'type(None)()' was probably judged to be more likely to
> be a bug than something useful.

Obviously people are unlikely to write type(None)(), but they are likely 
to do something like:

result = call_some_function(args)
more_code_here()
blah_blah_blah()
new_obj = type(result)()
do_something_with(new_obj)

If result happens to end up being None, I'm not convinced that the caller 
would rather have an exception than get the obvious None. If result 
happened to be 0, wouldn't you rather get 0 than have it blow up? I don't 
see why None should be any different.


>  > while bool returns the appropriate existing singleton: [sic]
> 
> Branching on boolean values (which are no more singletons than 0, 1,
> ...) is basic to computing.

What does that have to do with the price of fish? I didn't mention 
anything about branching on bools.

Once a singleton class has been instantiated the first time, you have a 
choice if the user tries to instantiate it again. You can do what 
NoneType does, and raise an error. Or you can do what bool does, and 
return the existing instance.

Obviously, the behaviour of bool is far more useful. So I wonder why 
NoneType doesn't do the same.



>> I wonder why NoneType doesn't just return None?
> 
> What would you have NoneType(x) do? 

The same thing any function of zero arguments does when it gets called 
with one argument.


> Or the special case NoneType(None)?

Why would that be a special case? If NoneType takes no arguments, and you 
supply an argument, then it is an error regardless of what that argument 
happens to be.


-- 
Steven



More information about the Python-list mailing list