Select to view content in your preferred language

Understanding arcpy.mp's addLayerToGroup

539
2
04-16-2024 06:56 AM

So, I'm genuinely confused by this.

I have a python script tool that needs to go find a SID file in our directory, pull it into the map, and add it to an already-existing Group Layer.

The Group Layer is provided to the tool by the user.

Simplified code below:

aprx = arcpy.mp.ArcGISProject('CURRENT')
mxd = aprx.activeMap

recordLayerGrp = arcpy.GetParameter(7) # Note that I'm not pulling as Text;
                                       #   this comes through as an
                                       #   arcpy.mp.Layer object

# [... intermediate code where I work with this and other layer objects just fine...]

mxd.addLayerToGroup(recordLayerGrp,  # At the point the function gets this 
                                     #   variable, it's unchanged from input;
                                     #   I pass it directly from the input
                                     #   function to this function.
                    fileLayerObj,    # This is also an arcpy.mp.Layer object
                    'TOP',
                   )

 This consistently fails with a ValueError.  After a bunch of headache, I managed to determine that said error is referencing the arcpy.mp.Layer object behind recordLayerGrp.

 

I went and did quite a bit of spelunking on this issue yesterday and today, and finally added a single line to the code (line 2, below):

recordLayerGrp = arcpy.GetParameter(7)
recordLayerGrp = [lyr for lyr in mxd.listLayers() if lyr.name == recordLayerGrp.name][0]

 

The result of this is still an arcpy.mp.Layer object, but it's a different instance.  And this different one suddenly magically works.  I even added debug statements before and after line 2, to see what was in recordLayerGrp at each step:

MErikReedAugusta_0-1713275709137.png

 

The tool inputs directly ask for the Group Layer and the user selects it.  Why did I have to "convert" the arcpy.mp.Layer object and go look for that Group Layer again?  Why doesn't the tool pull the "correct" instance of that object?

------------------------------
M Reed
"The pessimist may be right oftener than the optimist, but the optimist has more fun, and neither can stop the march of events anyhow." — Robert A. Heinlein, in Time Enough for Love
0 Kudos
2 Replies

Don't want to edit the original post because of this forum's added-line bug.

Here's the tool side of that parameter:

MErikReedAugusta_0-1713275907815.png

 

------------------------------
M Reed
"The pessimist may be right oftener than the optimist, but the optimist has more fun, and neither can stop the march of events anyhow." — Robert A. Heinlein, in Time Enough for Love
0 Kudos
BlakeTerhune
MVP Regular Contributor

Your mxd variable name is messing with me! What version of Pro are you using?

0 Kudos