On Mar 4, 7:32 pm, Steven D'Aprano <st...@remove-this- cybersource.com.au> wrote: > > Python does have it's own singletons, like None, True and False. For some > reason, they behave quite differently: NoneType fails if you try to > instantiate it again, while bool returns the appropriate existing > singleton: > > >>> NoneType = type(None) > >>> NoneType() > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: cannot create 'NoneType' instances>>> bool(45) > > True > > I wonder why NoneType doesn't just return None? >
It's an interesting question. Just to elaborate on your example: >>> type(None)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot create 'NoneType' instances >>> type(True)(False) False >>> type(False)(True) True I suspect that the answer is just that None is special. There is probably just no compelling use case where you want to clone None in a one-liner. To make None work like True/False in certain use cases you'd want something like this: def clone(val): if val is None: return None else: return type(val)(val) The same method would work against some non-singletons as well, although I'm not sure what the desired semantics would actually be: for value in [None, False, True, 42, [1, 2, 3]]: print clone(value) -- http://mail.python.org/mailman/listinfo/python-list