there is no such thing as the "sum" operator for difference (which is not permutable), so you should test the validity of each item to decide how you run the substraction.
def stack(item1,item2):
if item1 != None and item2 != None:
return item1-item2
elif item1 != None:
return item1
elif item2 != None:
return -item2 #added minus if item2 > item1 and result should be negative
else:
return None
alternatively, you could compute the difference between the first valid item and the sum of the following items (just need to check that there is at least one item)
def stack(item1,item2,item3,item4):
itemList = [item1,item2, item3, item4]
myList = [item for item in itemList if (item != None)]
if len(myList)>0:
return myList[0]-sum(myList[1:]) #difference between the first item and the rest of the list
else:
return None
As a remark, you need to choose a rule when you don't have enough valid fields. Null values are not supported with all database, but is the best solution in my opinion. Also note that you can change the minimum number of valid fields with the len(myList)>some_value condition
EDIT: if your "null" values are in fact "zeros", you can also replace the null values with zero in your list. That make the code even shorter.
def stack(item1,item2,item3,item4):
myList = [item if (item != None) else 0 for item in [item1,item2, item3, item4] ]
return myList[0]-sum(myList[1:])