Search code examples
pythonnonetype

Handling None when adding numbers


I would like to perform addition of 2 integers, which can also be None, with the following results:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b

What is the most pythonic, concise expression for this? So far I have:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b

or

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b

Is there any shorter way to achieve it?


Solution

  • This is reasonably compact and can handle different numbers of terms:

    def None_sum(*args):
        args = [a for a in args if not a is None]
        return sum(args) if args else None