Proposal: === and !=== operators

Steven D'Aprano steve at pearwood.info
Wed Jul 9 03:00:52 EDT 2014


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.

* To support non-reflexive types, allow === and !=== operators, which
  are like == and != except they don't call `is` first.

* The new === and !== operators call __eeq__ and __ene__ (extended
  equal and extended not equal) methods; if they don't exist, they
  fall back on __eq__ and __ne__.

* To support multi-valued logics, === and !== are not required to
  return True or False, they can return anything you like and it is
  up to the caller to ensure that they are sensible.

* Returning NotImplemented from __eeq__ and __ene__ has the same 
  meaning as for __eq__ and __ne__.

* For the avoidance of doubt, `if...elif...else` are not expected to
  be aware of multi-valued logics. No other changes to the language 
  are expected.


Thoughts? Comments?



-- 
Steven



More information about the Python-list mailing list