Search code examples
python-2.xminnonetype

Python2 - using min/max on None type


I noticed that while the 'max' function do well on None type:

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

'min' function doesn't return anything:

In [2]: min(None, 1)
In [3]: 

Maybe it's because there is no definition for min(None, 1)? So why in max case, it return the number? Is None treated like '-infinity'?


Solution

  • As jamylak wrote, None is simply not printed by Python shells.

    This is convenient because all functions return something: when no value is specified, they return None:

    >>> def f():
    ...     print "Hello"
    ...     
    >>> f()
    Hello
    >>> print f()  # f() returns None!
    Hello
    None
    

    This is why Python shells do not print a returned None value. print None is different, though, as it explicitly asks Python to print the None value.


    As for comparisons, None is not considered to be -infinity.

    The general rule for Python 2 is that objects that cannot be compared in any meaningful way don't raise an exception when compared, but instead return some arbitrary result. In the case of CPython, the arbitrary rule is the following:

    Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

    Python 3 raises an exception, for non-meaningful comparisons like 1 > None and the comparison done through max(1, None).


    If you do need -infinity, Python offers float('-inf').