Strict comparisons in Python 2

Terry Reedy tjreedy at udel.edu
Tue Oct 13 22:38:13 EDT 2015


On 10/13/2015 9:43 AM, Steven D'Aprano wrote:
> In Python 3, comparisons between arbitrary types raise TypeError:
>
> py> None < 2
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> TypeError: unorderable types: NoneType() < int()
>
>
> In Python 2, that same comparison will arbitrarily return True or False,
> according to some implementation-dependent rule.
>
> Is there some way to force the Python 3 rules into Python 2? Something like
> a __future__ import?

Not what you want, but ...

1. Only compare instances of classes with rich comparison methods that 
act as in Py 3, subsetting or wrapping builtins as needed.

2. Replace binary operation such as `None < 2` with

a. Conditional expression:
    None < 2 if compatible(a, b, comp) else None
    where compatible returns True for py3, True or TypeError for py2

b. Generic comparison function compare(a, b, comp):
    if compatible(a, b, comp):
       if comp = 'lt': return a < b

c. Specific comparison functon, such as lt(a, b).

I think a 2&3 package should have something like 2c, but I don't know
any particulars.

-- 
Terry Jan Reedy




More information about the Python-list mailing list