Is An Element of a Sequence an Object?

Steve D'Aprano steve+python at pearwood.info
Fri Jun 9 07:52:32 EDT 2017


On Fri, 9 Jun 2017 02:04 pm, Lawrence D’Oliveiro wrote:

> I generally have very little use for “is” in my code. I do try it out for
> testing sometimes, to ensure consistency of semantic behaviour in library
> bindings for example, but I don’t think I have ever written an “is”-construct
> in production code.

If you are using None as a sentinel value, and testing for None with ==
(equality) instead of identity (is), then you have a bug waiting to strike.

    if obj == None:
        # do special behaviour that is intended to ONLY occur if obj is None


Using equality there is wrong (as well as needlessly slow). The problem is that
Python will call obj.__eq__ which has a chance to claim to be equal to None. If
it does, then you will run the "only run for None" code for something that
isn't None.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list