I would like to use python to calculate a field (short integer) using other fields (short integer) present in the table. In some cases these fields may have NULL values for one or more of the fields. For example, the new field name is 'total' and total is based upon adding field01 + field02 + field03. Some records (rows) have values for field01, field02, and field03, but some rows only have values for field1 and field2, then field3 is NULL.

I have some code that I believe will work, but I must not be implementing it correctly.

#calculate new field 'total' in feature class 'test'
exSummed = "stack(!field01!+!field02!+!field03!)"
codeBlock = "def stack(*args):
    return sum(filter(None, args))"

arcpy.CalculateField_management(inFeatures, fieldName01, exSummed, "PYTHON", codeBlock)

Here is the error I receive...

enter image description here

Thanks -al

UPDATE: @Jason was correct, the triple double quote was my problem. I also modified my code based upon a suggestion posted here.

This is my updated code to reflect my solution:

import sys, string, os, arcpy
from arcpy import env

# Set workspace
env.workspace = "Q:/LandTrendr_04/lt_ancillary/landtrendr_file_geodatabase/templates_testing/LandTrendr_PIRO.gdb"

#calculate new field 'total' in feature class 'test'
exSummed = "stack(!field01!,!field02!,!field03!)"
codeBlock = """def stack(field01,field02,field03):
    itemList = [field01,field02,field03] 
    myList = [item for item in itemList if (item !=None)] 
    return sum(myList)"""

arcpy.CalculateField_management(inFeatures, fieldName01, exSummed, "PYTHON", codeBlock)

2 Answers 2


One of the examples on the tool's help page shows the use of triple quotation marks when specifying the code block, i.e.:

codeBlock = """def stack(*args):
    return sum(filter(None, args))"""

Try this and see if that helps. The difference being that you can include line breaks when using triple-quotes.


You can simplify your code by using 'or' (which will convert your null-None fields to 0...) This way you can get rid of your (sometimes hard to debug) codeblock...

inFeatures = 'test'
fieldName01 = 'total'
exSummed = "(!field01! or 0) + (!field02! or 0) + (!field03! or 0)"

arcpy.CalculateField_management(inFeatures, fieldName01, exSummed, "PYTHON", "")

'or' also works good when you're trying to concatenate (possible None) strings together...

exSummed = "(!field01! or '') + (!field02! or '') + (!field03! or '')"
  • Thanks for the much simpler code @Jason. I removed the codeblock and used the 'or 0' and it works great. Thanks again.
    – Al K
    Commented Mar 3, 2014 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.