Skip to content

Instantly share code, notes, and snippets.

@danmaps
Created August 21, 2023 20:01
Show Gist options
  • Save danmaps/057a7b38924c86b0767f394e1d85f171 to your computer and use it in GitHub Desktop.
Save danmaps/057a7b38924c86b0767f394e1d85f171 to your computer and use it in GitHub Desktop.
Validate and calculate fields
def validate_and_calculate_field(layer, field, expression):
# Validate field exists
fields = [f.name for f in arcpy.ListFields(layer)]
if field not in fields:
raise ValueError(f"Field {field} does not exist in layer")
# Validate expression fields exist
def get_fields_from_expression(expression):
matches = re.findall(r"!\w+!", expression)
return [m[1:-1] for m in matches]
expr_fields = get_fields_from_expression(expression)
missing_fields = set(expr_fields) - set(fields)
if missing_fields:
raise ValueError(f"Expression contains invalid fields: {missing_fields}")
# Calculate field if valid
arcpy.management.CalculateField(layer, field, expression, "PYTHON3")
# usage
validate_and_calculate_field("somelayer", "TARGETFIELD", "!SOME_FIELD!.upper()+'_'+!SOME_OTHER_FIELD!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment