3

I am creating a custom geoprocessing tool and I only want it to run if at least 1 feature in a layer is selected. However when I use the GetCount tool if no features are selected it gives me the number of total features in the feature class. Using the simple code below will give me the result of 1,2,3 etc if that many features are selected but if none are selected I get 34 instead of 0.

Is there another tool or way to have it give me the result of 0 if no features are selected?

I basically want to tell my tool if result >= 1 run the rest of the code.

import arcpy
StormInlets = "StormInlet_Test"
result = arcpy.management.GetCount(StormInlets)
print(result)

2 Answers 2

6

Try arcpy.da.Describe() on the layer and looking at the FIDSet property. It'll return a list of selected FIDs, or None if there is no selection.

desc = arcpy.da.Describe(layer)
has_selection = bool(desc.FIDSet)
print(has_selection)
0
2

Looking at Layer - ArcGIS Pro | Documentation and Layer - ArcMap | Documentation, there is a layer method that can be called directly to get selection information: getSelectionSet().

Calling layer.getSelectionSet() is better than calling describe.FIDSet for both performance and functional reasons. On the performance side, having to instantiate a Describe object is an extra step and cost when one can get the same information from a layer directly. More importantly, getSelectionSet() recognizes the difference between no selection and a selection with no records whereas FIDSet returns the same empty string in both situations.

>>> arcpy.management.SelectLayerByAttribute(layer, 'NEW_SELECTION', "1=1")
<Result 'layer'>
>>> print(layer.getSelectionSet())
{1, 2, 3, 4, 5}

>>> arcpy.management.SelectLayerByAttribute(layer, 'NEW_SELECTION', "1=2")
<Result 'layer'>
>>> print(layer.getSelectionSet())
set()

>>> arcpy.management.SelectLayerByAttribute(layer, 'CLEAR_SELECTION')
<Result 'layer'>
>>> print(layer.getSelectionSet())
None

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.