easy question on parsing python: "is not None"
steve at REMOVE-THIS-cybersource.com.au
Sat Aug 7 00:23:05 CEST 2010
On Fri, 06 Aug 2010 05:28:40 -0700, DG wrote:
> I've always thought of it as you don't compare strings with "is", you
> *should* use == The reasoning is that you don't know if that string
> instance is the only one in memory.
This is excellent advice. I won't say that there is "never" a use-case
for testing strings for identity, but I can't think of one that isn't
contrived and artificial.
> I've heard as an implementation
> detail, since strings are immutable, that Python will only create one
> actual instance and just assign new references to it (your first x is y
> example), but to compare equality it just makes sense to use "==", not
> to ask if it is the same object in memory. Plus, I believe the "=="
> operator will check if the variables point to the same object.
Yes, that is an optimization that CPython performs. Other implementations
may do different, but the optimization is so obvious and so cheap that I
would be shocked if any of the major implementations fail to do so.
> Using is/is not with None works well, because I believe there will
> always only be 1 None object.
Yes, that is correct, but there's also a semantic difference. Generally,
when testing for None, you actually want None and not some look-alike
that merely tests equal to None. You want to "accept no substitutes", and
so an identity test is necessary.
More information about the Python-list