Understanding syntax for CalculateField_management in ArcPy?

I never understand why people even try to mess with CalculateField_management within a Python script instead of just doing their updates within an UpdateCursor.

Not only do you not have to worry about escaping characters and writing Python functions within Python strings (shudder), you can update multiple fields at once.

It's very easy with the newer arcpy cursor iteration syntax:

rows = arcpy.UpdateCursor(fc)
for row in rows:
    row.DESCRIP = "%s Touchdown Zone Elevation;duplicated from existing control point;%s" % (str(enddesg), row.DESCRIP)
    rows.updateRow(row)
del rows

The magic on the row.DESCRIP = line is called string formatting in Python -- in this case it wasn't that necessary but when you're concatenating more than a couple of strings or need some specific numeric formatting it's really handy.

The other thing to note is that instead of hardcoding the field name (row.DESCRIP) you can also get and set field values using a variable to specify the field using row.getValue and row.setValue instead.

For the most part, I would suggest using getValue and setValue as it makes your code much easier to maintain if the field name changes or you want to write a generic function or script tool with the field name(s) as parameters.


I might be wrong, but I believe you are not supposed to put the field name !DESCRIP! in the code block. Use a placeholder variable and it should function properly.


In my testing, calling str() on an argument in your expression causes the tool to fail. Maybe try:

expr = "getDescription(enddesg, !DESCRIP!)"
codeblock = """def getDescription(endstr, desc):
    exprstr = str(endstr) + ' Touchdown Zone Elevation;duplicated from existing control point;' + desc
    return exprstr"""