2

I am using ArGIS Desktop Standard 10.4.1 with Python 2.7.11, and am a S elf-taught Python scripter.

I've researched this extensively but there doesn't appear to be anything newer than 2014.

I am trying to test if a feature layer has a selection or not. I'm doing this via my own python script in ArcToolbox.

Essentially what is happening is that the length of len(arcpy.Describe(lyr).fidSet.split(";")) when no features are selected is returning 1. Prior posts on this subject indicate that it should return 0. Below is some very simple code:

lyr = arcpy.GetParameterAsText(0)    # parameter is a feature layer

arcpy.AddMessage(len(arcpy.Describe(lyr).fidSet.split(";")))
arcpy.AddMessage(arcpy.Describe(lyr).fidSet.split(";"))

if len(arcpy.Describe(lyr).fidSet.split(";")) > 0:
    arcpy.AddMessage("Has Selection")
else:
    arcpy.AddMessage("No Selection")

If zero feature are selected this returns

1
[u'']
Has Selection

If one feature is selected it returns

1
[u'5']
Has Selection

If more than one feature is selected it returns

9
[u'1', u' 2', u' 3', u' 4', u' 5', u' 6', u' 7', u' 8', u' 9']
Has Selection

I've tried testing the returned string with is None and also putting not in front of the length statement, but those still return Has Selection when no features are selected.

2

As you know, FIDSet returns a list of ID in a string, separated with a semi-colon.

Your problem is not really a arcpy problem, but it is due to the fact that .split(delimiter) returns a non empty list (see SO for more details).

So, in fact, you should simplify your test: test for FIDSet==0 and it will be tell you when there are no selected elements.

if len(arcpy.Describe(lyr).fidSet) == 0: # alternatively: if arcpy.Describe(lyr).fidSet =='' :
    print "nothing selected"
else:
    print "{} elements selected".format(len(arcpy.Describe(lyr).fidSet.split(";"))
2

arcpy.Describe (lyr).FIDSet returns an empty string ('') when no selection is present. Empty strings return False in a logic test. Thus, use:

if arcpy.Describe (lyr).FIDSet:
    #selection
else:
    #no selection

enter image description here


enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.