Proposal: === and !=== operators

Alex Burke alexjeffburke at gmail.com
Thu Jul 10 12:33:34 EDT 2014


On 9 July 2014 09:00, Steven D'Aprano <steve at pearwood.info> wrote:
> At the moment, Python has two (in)equality operators, == and != which
> call __eq__ and __ne__ methods. Some problems with those:
>
>
> * Many people expect == to always be reflexive (that is, x == x for
>   every x) but classes which customise __eq__ may not be.
>
> * The == operator requires __eq__ to return True or False
>   (or NotImplemented) and raises TypeError if it doesn't, which
>   makes it impossible to use == with (say) three-valued or fuzzy
>   logic.
>
>
> I propose:
>
> * The == operator be redefined to *always* assume reflexivity, that
>   is, it first compares the two arguments using `is` before calling
>   the __eq__ methods.
>
> * That's a backwards-incompatible change, so you need to enable it
>   using "from __future__ import equals" in Python 3.5, and then to
>   become the default behaviour in 3.6.

(course I forgot to reply-all first first time I sent this)

Hi,

Aside from really reaching for Python for all my own projects (mostly
due to enjoying the language and it's design) the day job is mostly writing
server side code for Javascript on node.js. With that perspective I really
think those extra operators will cause confusion - granted the distinction
between == and === is for different reasons there but it's just complexity
to need to explain why there are different modes of comparison. With ==
and is I think when to use which is much more clear cut.

That being said though the point you raised that:
    different objects can implement __eq__ such that it may or may not be
    reflexive in different cases
could do with an answer. It's the implicitness and differing behaviour that
get me, and it seems to be one of the roots of the disagreement. When
should NaN compare equal, when not etc.

So, (this is likely a terrible idea) what if == was made always always reflexive
and a from __future__ to have any NaN being compared raise a new
NonReflexiveComparison exception? Advantages:
* no equality special cases to explain
* make potentially meaningless comparisons immediately clear
* if you really want to compare NaNs you can catch the case and
  return math.isnan(left) and math.isnan(right)

The obvious issue is possibility of exceptions from arbitrary == comparisons.

PS hoping these comments comments might prove useful :-)

Thanks, Alex J Burke.



More information about the Python-list mailing list