On Tue, Aug 31, 2021 at 5:34 AM Nick Parlante <n...@cs.stanford.edu> wrote:
>
> Hi Chris - thanks for the response,
>
> so here you say:
>
>> I disagree; experienced programmers should be using "is" where it's
>> correct.
>
>
> I'd like to unpack that a little - like what do you mean by "correct" there. 
> My guess is "correct" means the code gets the right answer for all inputs.
>
> Like for "if x == None:" works right
>
> By that definition, == is correct there. I think PEP8 has forced people to 
> use "is" so much, they've lost touch with the reality that in fact == would 
> work perfectly in almost all cases. Situations where "is" is required for 
> correctness are very rare.
>

class X:
    def __eq__(self, other): return True

Now your code is broken, because it will accept an instance of X when
it should only be accepting None.

It's also broken if you use numpy:

>>> if numpy.array([1,2,3]) == None: pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

So, no, == is not correct. (Which reads weirdly, but it's still True,
since correct is not the equals-equals operator.)

These distinctions probably don't matter to a novice, but experienced
programmers should know (or be able to figure out) whether they're
looking for an identity check or an equality check. There are a few
rules of thumb to help:

1) If you're comparing numbers or strings (Unicode or byte), use
equality, because there could be multiple that have equivalent values.
(Easiest to demonstrate with numbers since 5 == 5.0 == Fraction(5) ==
Decimal("5") but also true of strings in CPython.)

2) If you're checking for sentinel objects (None, Ellipsis, etc), use is.

3) Otherwise, use == unless you know you're doing an identity check.

That'll cover most situations. I wouldn't bother teaching the
distinction until you're looking at mutable objects (for instance, []
== [] because they currently have the same value, but if you append
something to one of those lists, they won't; and you can use 'is' to
figure out whether two things are actually the same list).

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PWXR4VHVOZHVY7FOY5HXOB3BUPHM7ZHV/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to