4

I'm trying to create the following in ModelBuilder:

Set input feature class
  if field1 exists
    execute the processes in branch1
  else
    add field1
    execute the processes in branch2
    merge branch

While I have no problem with the processes in the two branches, the IF check at the start doesn't seem to be working the way I want it to work. I am using this code in the Calculate Value code block

def ifFieldExists(Input_FC, SUMMARY):
  import arcpy
  fields = arcpy.ListFields(Input_FC)
  for f in fields:
    if f ==" SUMMARY":
      return "true"
    else:
      return "false"

and expression

ifFieldExists(r"%Input_FC%", "%SUMMARY%")

This is the precondition for branch1, so if it returns true, the field exists so branch1 executes. The other branch's precondition returns the reverse. When I run it on an input that does contain the field, the precondition returns false instead of true, so the wrong branch executes.

1 Answer 1

3

There are a number of logic errors and possible improvements/simplifications here:

  • ListFields returns a list of Field objects, not strings corresponding to the field names, so you should check the field object's name property instead of directly equating the field object to the desired field name.
  • You've hardcoded the string " SUMMARY" (note the leading space) instead of using the function parameter SUMMARY (I would also rename that to field or fieldName for clarity).
  • You're looping through the list of fields but return either true or false on the first iteration. This means that if the first field in the list is not the one your looking for, you will always return false, even if the correct field exists further down the list. If you do use this type of logic you would need to let the loop continue and only return false after the loop has completed without first returning true (omit the else statement and un-indent the return "false" statement so that it is outside of the loop).
  • ListFields accepts a wildcard argument, allowing you to limit which fields are returned. You could then check whether the length of the returned list is greater than 0 and return true if so, or false if not.
  • You don't need the import arcpy statement, it is always available from the ModelBuilder environment.

So to sum up, try something like the below instead of what you have currently:

def ifFieldExists(inputFC, fieldName):
  fields = arcpy.ListFields(inputFC, fieldName)
  return "true" if len(fields) > 0 else "false"
1
  • I didn't even notice the space before SUMMARY. This worked perfectly, and I added another Calculate Value to return the opposite so that both branches now have a precondition that will return true. Thanks! Commented Jul 6, 2012 at 5:12

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.