AnsweredAssumed Answered

Lessons Learned - Deleting In Memory Layers Can have Unexpected Results

Question asked by david.plume on Aug 31, 2015
Latest reply on Sep 2, 2015 by david.plume

I recently ran in to a confounding and scarry problem processing feature classes and layers that I'd like to share in the hopes this will save others from much pain and grinding of teeth!  I'm interested in any better strategies too.  Thanks.

 

As many of you know, when creating layers using in a looping situation such as:

 

arcpy.MakeFeatureLayer_management(pFc, "MYLAYERNAME")

 

requires deletion of "MYLAYERNAME" on each subsequent iteration using code like this:

 

try:

arcpy.Delete_management("MYLAYERNAME")

except:

pass

 

Recently I bumbled into a situation where I thought I'd use the baseName of the featureclass as the in memory layer name -- this is a big mistake because deletion actually deleted the featureclass! Doh.

 

The pattern that you actually want is something like this:

 

       sLayName = "TEMPLAY"  #DONT USE THE NAME OF THE FEATURE CLASS HERE.  If you do you'll delete the FC

 

try:

arcpy.Delete_management(sLayName)

except:

pass

 

try:

arcpy.MakeFeatureLayer_management(pFc, sLayName)

pLay = arcpy.mapping.Layer(sLayName)

 

pLay.name = desc.baseName   # HERE is Where you apply the baseName to the Layer

 

arcpy.mapping.AddLayerToGroup(df, pGroupLayer, pLay, "AUTO_ARRANGE")

 

except:

    arcpy.AddMessage("Problem Creating Layer")

Outcomes