Python min / max on None type

I noticed that although the "max" function works well on the None type:

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

'min' returns nothing:

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

Maybe because there is no definition for min (None, 1)? So why, in the maximum case, does it return a number? Is it considered an "infection"?

+7
source share
3 answers

As jamylak wrote, None 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 the return value of None. print None is different, however, because it explicitly requests Python to print the None value.


As for comparisons, None not considered an infection.

The general rule for Python 2 is that objects that cannot be compared in any meaningful way do not throw an exception in comparison, but instead return some arbitrary result. In the case of CPython, an arbitrary rule is as follows:

Objects of different types, except numbers, are sorted by type; objects of the same types that do not support proper comparison are ordered by their address.

Python 3 throws an exception for meaningless comparisons such as 1 > None and comparisons done with max(1, None) .


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

+7
source

It returns something, python shell just doesn't print None

 >>> min(None, 1) >>> print min(None, 1) None 
+7
source

If you really need a value that will always compare less than any other, you need to create a small class:

 class ValueLessThanAllOtherValues(object): def __cmp__(self, other): return -1 # really only need one of these ValueLessThanAllOtherValues.instance = ValueLessThanAllOtherValues() 

This class will compare with values โ€‹โ€‹of any other type:

 tiny = ValueLessThanAllOtherValues.instance for v in (-100,100,0,"xyzzy",None): print v print v > tiny print tiny < v # use builtins print min(tiny,v) print max(tiny,v) # does order matter? print min(v,tiny) print max(v,tiny) print 

Print

 -100 True True <__main__.ValueLessThanAllOtherValues object at 0x2247b10> -100 <__main__.ValueLessThanAllOtherValues object at 0x2247b10> -100 100 True True <__main__.ValueLessThanAllOtherValues object at 0x2247b10> 100 <__main__.ValueLessThanAllOtherValues object at 0x2247b10> 100 0 True True <__main__.ValueLessThanAllOtherValues object at 0x2247b10> 0 <__main__.ValueLessThanAllOtherValues object at 0x2247b10> 0 xyzzy True True <__main__.ValueLessThanAllOtherValues object at 0x2247b10> xyzzy <__main__.ValueLessThanAllOtherValues object at 0x2247b10> xyzzy None True True <__main__.ValueLessThanAllOtherValues object at 0x2247b10> None <__main__.ValueLessThanAllOtherValues object at 0x2247b10> None 

tiny even smaller than himself!

 print tiny < tiny True 
-one
source

All Articles