Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max() fails in python2 -> python3 conversion with `>` not supported

While converting from python 2.x -> python 3.x, I found this change in the behavior of the built-in max function. I didn't find it documented in any of the standard locations for migration issues. https://eev.ee/blog/2016/07/31/python-faq-how-do-i-port-to-python-3/ http://python-future.org/compatible_idioms.html

How do I fix this?

Python 2.x:

In [1]: max([None, None, None])
In [2]: 

Python 3.x:

In [3]: max([None, None, None])
---------------------------------------------------------------------------
TypeError                                
Traceback (most recent call last) <ipython-input-3-f82c85b9875c> in <module>()
----> 1 max([None, None, None])

TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'
like image 748
Shankari Avatar asked Sep 23 '26 18:09

Shankari


1 Answers

Answering my own question: there is no backwards compatible max, but it is arguable that trying to find the max of None doesn't really make sense.

The entries that I was comparing were timestamps, and I knew that they would never be negative. So I changed my code to return 0 instead of None, so the max turned to max([0,0,0]) which worked.

If you can't make such guarantees about your data, you could return -sys.maxsize instead.

In [7]: max([-sys.maxsize, -sys.maxsize, -sys.maxsize])
Out[7]: -9223372036854775807

Note sys.maxsize not sys.maxint, which is a documented change. What is sys.maxint in Python 3?

like image 93
Shankari Avatar answered Sep 26 '26 08:09

Shankari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!