Using ArcPy and a set to apply a definition query

2761
1
10-31-2019 01:33 PM
MelissaDaniels1
New Contributor III

I'm trying to use ArcPy to apply a definition query to a layer based on a selection.

First, I figured out how to use ArcPy to apply a definition query.

This runs fine in a console, but won't run properly within the ArcGIS Pro Python console. That's unrelated to my current issue, but I would love tips on why that's happening

import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Users\melis\Documents\GISPortfolioProjects\CustomTools\Sel2DefQuery.aprx") 
m = aprx.listMaps("Map")[0]
l = m.listLayers("parcels_centroid")[0]
l.definitionQuery = '""State_1" = \'VA\'"'
aprx.save()

Then I separately found out how to access the OIDs of the selected features.

Again, this runs fine in a console but not in the ArcGIS Python window.

import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Users\melis\Documents\GISPortfolioProjects\CustomTools\Sel2DefQuery.aprx") 
m = aprx.listMaps("Map")[0]
l = m.listLayers("parcels_centroid")[0]
print (l.getSelectionSet())‍‍‍‍‍‍‍

This code gives the result {19,21} which is in the form of a set.

So then I need to combine these two. This is what I have so far. It doesn't work. I can't figure out how to integrate the set into the SQL statement.

import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Users\melis\Documents\GISPortfolioProjects\CustomTools\Sel2DefQuery.aprx") 
m = aprx.listMaps("Map")[0]
l = m.listLayers("parcels_centroid")[0]
OIDs = l.getSelectionSet()
l.definitionQuery = '"OBJECTID" IN' + "'%s" %OIDs
aprx.save()

I know there's something in my syntax that doesn't make sense, but I'm not very experienced with Python, and I've tried many variations of this statement and still can't get it to work. Is my problem that it's a set not a list? Or am I just trying to do it wrong?

I would very much appreciate any guidance on how to get the SQL statement / definition query to work, and thoughts on why it runs fine in an outside console but not in the ArcGIS Python window.

Thanks!

0 Kudos
1 Reply
DanPatterson_Retired
MVP Emeritus

not sure I follow, but

r"C:\Users\melis\Documents\GISPortfolioProjects\CustomTools\Sel2DefQuery.aprx" is fine when pro isn't open, but

"CURRENT"

Tutorial: Getting started with arcpy.mp—ArcPy | ArcGIS Desktop 

as in

aprx = arcpy.mp.ArcGISProject("CURRENT")

if you are using the python window in Pro