Handling None when adding numbers

Viewed 6758

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?

3 Answers

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 

With boolean logic:

Here's a Pythonic method, using lazy or:

def add(a, b):
    return (a or 0) + (b or 0)

With filter

For an arbitrary number of summands, you could use filter and sum:

def add(*p):
    return sum(filter(None, p))

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None))
# 0
print(add(None, 0))
# 0

With an exception

Note that the previous implementations will return 0 for add(None, None). This is the expected mathematical result of an empty sum.

Returning None is suprising and might lead to TypeErrors when you use the output of add.

One way to achieve the desired behaviour when users don't input any valid summand is to throw an exception:

def add(*p):
    summands = list(filter(None, p))
    if not summands:
        raise ValueError("There should be at least one defined value.")
    return sum(summands)

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None, 0))
# 0
print(add(0))
# 0
print(add(None))
# ValueError: There should be at least one defined value
print(add())
# ValueError: There should be at least one defined value

Try this

def add(a,b):
    a = 0 if not a else a
    b = 0 if not b else b
    return a+b
Related