Hello, I'm trying to change the symbology of a feature class (symbology is unique values based on a field within the attribute) and add some definition queries. However, whenever I run the tool, it adds two duplicate output layers to the model.
I include a snippet of code below. I presume this is because I use addDataFromPath and SetParameter. But I don't see how I can avoid using these, since the tool requires SetParameter and to access the symbology I need to create a layer.
In which case, how do I prevent the layer being added twice?
- m.removeLayer(lyr) removes both layers
- This occurs regardless whether Add Outputs to Map is switched off or not in the aprx (env setting shouldn't (and doesn't) work in a python script)
- I have tried using a lyrx file for the symbology but the definition queries are not transferred
Any thoughts what I might be missing?
Many thanks in advance
Tom
import arcpy
input_fc = "File path to input feature class"
polygon_symbology = "Some Symbology Dict"
definition_query = "Set of Definition Queries"
field = "field name"
m = arcpy.mp.ArcGISProject("CURRENT").activeMap
lyr = m.addDataFromPath(input_fc)
sym = lyr.symbology
sym.updateRenderer('UniqueValueRenderer')
sym.renderer.fields = [field]
for grp in sym.renderer.groups:
for itm in grp.items:
myVal = itm.values[0][0]
arcpy.AddMessage(f"Applying symbology for {myVal}")
if myVal in polygon_symbology:
symbology_list = polygon_symbology[myVal]
arcpy.AddMessage(f"Applying symbology: {symbology_list}")
itm.symbol.applySymbolFromGallery(symbology_list[0])
itm.symbol.size = symbology_list[1]
itm.symbol.outlineColor = symbology_list[2]
else:
arcpy.AddMessage(f"Warning: {myVal} not found in descriptions. Skipping symbology assignment.")
lyr.symbology = sym
lyr.updateDefinitionQueries(definition_query)
arcpy.SetParameter(1, lyr)
arcpy.mp.ArcGISProject("CURRENT").save()
del m