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)
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Apr 26, 2023 at 16:26

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)
answered Apr 26, 2023 at 20:00
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
answered Aug 19, 2024 at 20:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.