singleton ... again

Robert Kern robert.kern at gmail.com
Thu Feb 13 16:13:21 EST 2014


On 2014-02-13 20:03, Chris Angelico wrote:
> On Fri, Feb 14, 2014 at 2:24 AM, Roy Smith <roy at panix.com> wrote:
>> In article <mailman.6834.1392292646.18130.python-list at python.org>,
>>   Chris Angelico <rosuav at gmail.com> wrote:
>>
>>> On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder <ned at nedbatchelder.com>
>>> wrote:
>>>> I still don't see it.  To convince me that a singleton class makes sense,
>>>> you'd have to explain why by virtue of the class's very nature, it never
>>>> makes sense for there ever to be more than one of them.
>>>
>>> There's a huge difference, btw, between mutable and immutable
>>> singletons. With immutables like None, True/False, integers, strings,
>>> and tuples thereof, returning a preexisting object is just an
>>> optimization. Do it if you want, don't if you don't, nobody's going to
>>> hugely care.
>>
>> People *depend* on None being a singleton (and are encouraged to do so),
>> when they use "is" as the test-for-Noneness.
>
> Circular argument, though. If None weren't a singleton, people would
> use == to test for Noneness. Since it's been guaranteed to be
> optimized to a singleton, the comparison can also be optimized, but
> it's still just an optimization, as can be seen with integers. In
> CPython, you could test for small integer equality using 'is', but
> since that optimization isn't guaranteed, neither is that code
> pattern.

We don't use `is None` instead of `== None` for the speed. We use it for 
robustness. We don't want arbitrary __eq__()s to interfere with our sentinel 
tests. If None weren't a singleton that we could use as such a sentinel, we'd 
make one.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list