I am attempting to remove duplicates in a feature class that are generated by a Python script. At the end of my script I have the code block below; I haven't implemented it yet, but would like to see if this is the correct way to use arcpy.da.Editor as the errors that I have been receiving are in regards to being outside of an edit session.
Is arcpy.da.Editor being used correctly here?
`
fields = ['OBJECTID', 'SRNumber', 'ItemLoc_9']
table_rows = []
delete_rows = []
where_clause = """ ItemLoc_9 = ' '"""
with arcpy.da.Editor(appendClass) as edit:
with arcpy.da.SearchCursor(appendClass, fields, where_clause) as cursor:
for row in cursor:
if [row[1], row[2]] in table_rows:
delete_rows.append(row[0])
else:
table_rows.append([row[1], row[2]])
del table_rows
with arcpy.da.UpdateCursor(appendClass, ['OBJECTID']) as cursor2:
for row in cursor2:
if row[0] in delete_rows:
print 'Deleting record: OBJECTID = ' + str(row[0])
cursor2.deleteRow()
print '\ndone'`
Best Answer
I have had lots of trouble/inconsistencies with this in the past. Instead, I have implemented some wrappers for both the update and insert cursors. This way, every time I run an update cursor, I know an edit session is properly started and stopped for the cursor. Here is my update cursor (with a helper function to get the workspace):
So if you save this somewhere in your PYTHONPATH and call the update cursor, you can always be sure that an edit session is started and stopped. This wrapper also allows the usage of the with statement for the cursor.
If you saved the script above as
some_module.py
and save it in your PYTHONPATH, you can call it like this: