steve+comp.lang.python at pearwood.info
Thu Aug 16 15:58:16 CEST 2012
On Thu, 16 Aug 2012 14:47:47 +0200, Hans Mulder wrote:
> On 8/08/12 04:14:01, Steven D'Aprano wrote:
>> NoneType raises an error if you try to create a second instance. bool
>> just returns one of the two singletons (doubletons?) again.
>> py> type(None)()
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: cannot create 'NoneType' instances
> Why is that?
> Why doesn't it just return an existing instance of the type, like bool,
> int, str and other built-in non-mutable types do?
bool must return an instance, because it is designed to cast objects to a
boolean. Since (by design) True and False are singletons (doubletons?),
bool(x) will always return a pre-existing instance.
Other built-in immutable types do not promise to do that. For example:
py> a = float(42)
py> b = float(42)
py> a is b
Sometimes int and str will cache their instances, but this is an
implementation detail subject to change without notice from version to
None, NotImplemented and Ellipsis are singletons, but unlikely bool,
there is no common use-case for having their types return the singleton
instance. The standard design pattern for singletons is to raise an
exception if you try to create an instance, so they do. However, this
behaviour really only makes sense for singletons that hold state. (If
they hold state, you might be tempted to change that state, not realising
that you are changing a singleton and not a second instance.)
In my opinion, this is a PITA for None and better behaviour would be to
return the pre-existing NoneType instance, but I didn't design the
More information about the Python-list