Trouble Accessing Layers with Python

4782
11
Jump to solution
04-13-2015 09:38 AM
RachaelJohnson
Occasional Contributor

In case you've been following my fairly boring saga: I am making progress on my program!  I have my files going where they need to go! Yay!

I am trying to remove intermediate and unnecessary layers from the map document.  I have a raster file, "SoilUnclass", that I want to remove from my map document to de-clutter my Table of Contents. I put the following code together based on what I've seen and read. I left my variable definitions out of the code but my inputs are all initialized with the proper file paths.

SoilUnclass = arcpy.PolygonToRaster_conversion(soil, "HSG", ScratchPath + r"\SoilUnclass",
   "MAXIMUM_COMBINED_AREA")
SoilClass = arcpy.sa.Reclassify(SoilUnclass, "HSG", arcpy.sa.RemapValue([["A", 1],
  ["B", 2],
  ["C", 3],
  ["D", 4],
  ["A/D", 14],
  ["B/D", 24],
  ["C/D", 34],
  ["---", 4]]), "NODATA")
SoilClass.save(WorkPath + r"\SoilClass")
SoilClass.save(GDBpath + r"\SoilClass")
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]
arcpy.mapping.RemoveLayer(df, SoilUnclass)

When I run that code, I receive the following error:

Runtime error

Traceback (most recent call last):

  File "<string>", line 2, in <module>

  File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\utils.py", line 182, in fn_

    return fn(*args, **kw)

  File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\mapping.py", line 1845, in RemoveLayer

    assert isinstance(remove_layer, Layer)

AssertionError

...?? It may be worth noting that when I do arcpy.mapping.ListLayers(mxd), "SoilUnclass" is not a layer that shows up.  Only the files that were in the map document before I ran my code are listed.  I saved my document and did ListLayers() again but nothing changed.  How can I get access to these layers to modify them?

0 Kudos
11 Replies
DarrenWiens2
MVP Honored Contributor

Ah, yes, there are some subtle differences running Python inside or outside of ArcMap. Glad it's making sense.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Your problem sounds familiar, not sure if I have run into it before or helped someone who has.

Anyhow, part of your problem is caused by misunderstanding the ArcPy Result object.  The result object from calling Polygon to Raster (Conversion), specifically the getOutput method of that result object, isn't a Layer object or even the name of a layer in the map document.  In this case, the result object is returning the path to the newly created raster dataset.  RemoveLayer is throwing an AssertionError because it needs a "reference to a Layer object representing the layer to be removed," which the string you are passing it from the result object isn't.

It appears you are having difficulties enumerating layers in the map document.  Can you provide a code snippet where you run the geoprocessing tool and attempt to list all the layers afterwards?