0

Suppose I make a temporary layer from a feature class in a gdb:

select = arcpy.MakeFeatureLayer_management("roads", "select_lyr", "FIPS_CODE = '06023'")

Later I want to see if that layer exists and if it does, delete it.

try:
    if arcpy.Exists(select):
        arcpy.Delete_management(select)
    else:
        print "select doesn't exist" 
except:
    pass

In this scenario, nothing happens. Assuming the layer gets deleted automatically , the print statement doesn't print, and if I just type >>> select in the console, I get a <Result Object>. What am I doing wrong here?! Do I even need to delete this (say I am creating hundreds of similar selects and I don't want it to run out of memory)? Do I need to add the arcpy.en.workspace = 'roads' or something before the delete?

  • 1
    You have deleted the layer in memory but not the variable, so now it points to nothing, it should be enough to del select and let python clean up the memory. – Michael Stimson Nov 6 '18 at 2:38
  • Why is it in a bare try/except block? You're throwing away the error messages you need to diagnose the issue – mikewatt Nov 6 '18 at 21:38
2

In your code select is a results object.

>>> lyr = arcpy.MakeFeatureLayer_management ("roads", "layer")
>>> type (lyr)
<class 'arcpy.arcobjects.arcobjects.Result'>

Use the layer name instead.

try:
    if arcpy.Exists("layer"):
        arcpy.Delete_management("layer")
    else:
        print "select doesn't exist" 
except:
    pass
  • 2
    To compliment this answer - I see this problem all the time, people treat result objects as if they are the output. I would go as far to say make it crystal clear and instead of calling the result object lyr (which in my opinion indicates its a layer object) call it something like resObj or even result. – Hornbydd Nov 6 '18 at 21:40
  • 1
    @Hornbydd, that's made even more confusing by the fact that using the result object as the input into another function works totally fine in most cases, since the string representation is usually the path to the output dataset. But obviously that can be dangerous as shown here since it's not totally consistent. I actually use that behavior quite often since it saves a bit of typing when creating temporary feature classes and whatnot – mikewatt Nov 7 '18 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.