[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

singleton ... again

On Fri, Feb 14, 2014 at 8:13 AM, Robert Kern <robert.kern at gmail.com> wrote:
> 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.

Sure. Yes, its identity is important as part of its being the Python
equivalent of C's null pointer. But the main point of singletons is to
be able to be "instantiated" without creating new elements; the
sentinel status of None is no different from the classic way of
recognizing the presence of an argument:

_SENTINEL = object()
def foo(arg1, arg2=_SENTINEL):
    if arg2 is not _SENTINEL: do_stuff_with(arg2)

That's not a singleton in that sense; it's just a unique object. You
could use [] for that instead of object() and it would work just the
same. So None is serving multiple purposes: it's an empty object, but
it's also a sentinel. In many uses, it wouldn't be a problem to have
more Nones floating around, hence it's mostly like your classic

My main point about mutable vs immutable is more clearly seen with
integers and strings. Some integers are cached; some strings are
interned; nobody particularly cares about the exact boundaries, except
when playing around with id() or introspection of some sort.