ArcGIS – Using If Then Else in ArcGIS Model Builder

arcgis-desktopmodelbuilderpython

I have a model which iterates through feature classes in a geodatabase.
For each feature class, it runs the check Geometry tool.
I then use the "Get Count" tool to count the number of rows in the output table.
I then want to add an expression where if the number of rows is greater than 0 it should keep running the rest of the model, otherwise it should go on to the next feature class.

I thought this could be achieved by using the Calculate Value tool using the following code.

Expression

CountMe(%Row Count%)

Code Block

 def CountMe(n):
     import arcpy
     if n > 0:
      return "true"
     else:
      return "false"

Where %Row Count% is the output from the "Get Count" tool.

This returns True and False values, and I have the output from this set as a precondition to the next steps in the model.

However, I assumed that only "true" data would go through, but all the data seems to go through i.e. the model will push through an empty table from the Check Geometry tool all the way to the end.

I've had a read online and I think that using the Calculate Value tool is the wrong way to go about this. Am I right in assuming that what I need is a python script that will give me 2 outputs (True and False) and then I can connect the "True" as a precondition to the rest of the model, and leave the "False" disconnected, so the model stops and the iterator goes on to the next feature class?

If so, would anybody be able to give me some help with this?

Model structure

Best Answer

If the precondition that checks for True or False is expecting a boolean, it will always evaulate to true because non-empty strings return true values, like so:

>>> if "true":      print "Really True!"

Really True!
>>> if "false":     print "Really True!"

Really True!

Have you tried returning True or False (booleans) instead of "true" or "false" (strings)? That might solve the issue.

def CountMe(n):         
     if n > 0:
      return True
     else:
      return False

The following is also equivalent to the above:

def CountMe(n):         
    return True if n > 0 else False

A few notes:

Importing arcpy (which seems unnecessary) can drastically slow down your code. If you have 1000 rows, you might very well be increasing run time by 15+ minutes.

enter image description here

Related Question