Hi, I am the process of converting a geoprocessing script from ArcMap & Python 2 to Pro & Python 3 and I've run into an annoying issue with the spatial join tool. My script takes a feature layer as input and then acts on the selection in that layer. This worked fine in ArcMap but in Pro arcpy's spatial join is clearing the layer selection after it runs. I am using ArcGIS Pro 3.1. Here is an example script that demonstrates the problem:
import arcpy
def get_selection_count(in_layer):
"""return the number of selected features in the layer"""
selection = in_layer.getSelectionSet()
if selection:
return len(selection)
return 0
# envs
arcpy.env.overwriteOutput = True
arcpy.env.workspace = arcpy.env.scratchGDB
# create test feature class
fc = arcpy.management.CreateFeatureclass(arcpy.env.scratchGDB, "test_point_fc", "POINT")[0]
points = [arcpy.Point(100, 100), arcpy.Point(200, 200)]
with arcpy.da.InsertCursor(fc, ["SHAPE@"]) as crsr:
for point in points:
crsr.insertRow((point,))
# make a layer
layer = arcpy.management.MakeFeatureLayer(fc, "test_layer")[0]
# make a selection
layer = arcpy.management.SelectLayerByAttribute(layer, "NEW_SELECTION", "1=1")[0]
print(f"There are {get_selection_count(layer)} features selected.")
arcpy.SpatialJoin_analysis(layer, layer, "out_sj")
print(f"There are {get_selection_count(layer)} features selected.")
Edit:
The output would be
There are 2 features selected.
There are 0 features selected.
Is this a bug? Am I missing something? Thanks.