Python 3 raising an error where Python 2 did not

Peter Otten __peter__ at web.de
Fri Aug 26 05:37:44 EDT 2016


dfh at forestfield.co.uk wrote:

> In a program I'm converting to Python 3 I'm examining a list of divisor
> values, some of which can be None, to find the first with a value greater
> than 1.
> 
> Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
> on win32 Type "help", "copyright", "credits" or "license" for more
> information.
>>>> None > 1
> False
> 
> Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64
> bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for
> more information.
>>>> None > 1
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unorderable types: NoneType() > int()
> 
> I can live with that but I'm curious why it was decided that this should
> now raise an error.

Because allowing comparisons between object of arbitrary type does more harm 
than benefit?

[Python 2]
>>> sorted([1, "2", 3])
[1, 3, '2']

In the rare case where you actually want to compare different types you can 
make that explicit:

[Python 3]
>>> sorted([1, "2", 3], key=int)
[1, '2', 3]
>>> sorted([1, "2", 3], key=lambda x: (type(x).__name__, x))
[1, 3, '2']
>>> sorted([1, "2", 3], key=lambda x: (not isinstance(x, str), x))
['2', 1, 3]
>>> from itertools import product
>>> for x, y in product([None, 1], repeat=2):
...     print(x, ">", y, "-->", (x is not None, x) > (y is not None, y))
... 
None > None --> False
None > 1 --> False
1 > None --> True
1 > 1 --> False





More information about the Python-list mailing list