Search code examples
pythonpython-3.xnonetypeshort-circuiting

No TypeError comparing int with None in Python3


I understand that comparing int and None types is not valid in Python3 (3.6.1) as I see here:

>>> largest = None
>>> number = 5
>>> number > largest
TypeError: '>' not supported between instances of int and NoneType

But inside this script it doesn't give a TypeError.

largest = None
for number in [5, 20, 11]:
    if largest is None or number > largest:
        largest = number

When I run this script with python3 it runs without a TypeError. Why?


Solution

  • You're witnessing short circuiting.

    if largest is None or number > largest:
            (1)        or      (2)
    

    When condition (1) is evaluated to be true, condition (2) is not executed. In the first iteration, largest is None is True, so the whole expression is true.


    As an illustrative example, consider this little snippet.

    test = 1
    if test or not print('Nope!'):
         pass
    
    # Nothing printed 
    

    Now, repeat with test=None:

    test = None
    if test or not print('Nope!'):
         pass
    
    Nope!