SelectLayerByAttribute empty selection

1794
3
04-04-2012 04:37 AM
RA1
by
New Contributor
How can I use the information from arcpy.SelectLayerByAttribute_management, when I have an empty selection?

If empty:
    do something
do somethingelse
Tags (2)
0 Kudos
3 Replies
MathewCoyle
Frequent Contributor
You can use getcount to test if there is a selection. You can reverse if you have no selection more often than not, or if you only want to be doing something if there is no selection.

selectcount= int(arcpy.GetCount_management(layer).getOutput(0))
if selectcount != 0:
    do something if a selection
else:
    do something else if no selection
0 Kudos
JamesNunn
New Contributor III
I have never been able to make this work as intended; running the script on a layer which has no selection just returns the total number of rows in the feature class. Below is a python function to count the number of rows in a selection using a SearchCursor:

def count_selection(lyr):
    """Returns a count of selected features from an input feature layer."""
    count = 0
    rows = arcpy.SearchCursor(lyr)
    for row in rows:
        count += 1
    return count


Example:

lyr = "Buildings_lyr"

if count_selection(lyr) == 0:
    print lyr, "is empty"


Not as neat as having a working inbuilt function; maybe someone can show me I am using the arcpy function incorrectly.
0 Kudos
ArkadiuszMatoszka
Occasional Contributor II
You can use Describe on layer and FIDSet property. It should looks like:

desc = arcpy.Describe(lyr)
if len(desc.FIDSet) > 0: # layer has selection
  doSomething
else:
  doSomethingElse


Cheers
Arek
0 Kudos