3

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'
Shankari
  • 389
  • 2
  • 4
  • 14

2 Answers2

1

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?

Shankari
  • 389
  • 2
  • 4
  • 14
-1

None represent the absence of a value in Python3 shows the error message ,because you dont search the largest item in arguments list of type NoneType