How to delete a Search Cursor that is never named

478
4
04-02-2018 01:05 PM
DougBrowning
MVP Esteemed Contributor

I just want a record count from a Search Cursor.

If I write a line like this

nom = len(list(arcpy.da.SearchCursor(pointLayer, fields, whereClause)))

do I have to worry about deleting the cursor for cleanup?  And if so how?

Or is something like this safer?

with arcpy.da.SearchCursor(pointLayer, fields, whereClause) as cursor:
    denom = len(list(cursor))

Or if I stick the cursor in a function will it release it when the function is done?

Thanks a lot

0 Kudos
4 Replies
DanPatterson_Retired
MVP Emeritus

with is usually good since it ensures that things get closed properly when done or things go wrong

https://docs.python.org/3/reference/compound_stmts.html#the-with-statement

https://docs.python.org/3/reference/datamodel.html#context-managers

As a little test, run your code snippet in your python IDE, then see if cursor still exists 

>>> locals().keys()  # is it there?

0 Kudos
DougBrowning
MVP Esteemed Contributor

I get this

['nom', 'pointLayer', 'surveyGeo', 'whereClause', '__builtins__', 'fields', '__file__', '__package__', 'sys', 'arcgis', 'time', '__name__', 'datetime', 'arcpy', '__doc__', 'math']

But with no name what am I looking for?

Thanks

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

If there are no references to the object, garbage collection will eventually take care of it.

Regarding counting records, there have been numerous discussions over the years on Esri forums, GeoNet, StackExchange, etc... about what are the "best" and "fastest" ways:

You should look into using Get Count—Data Management toolbox | ArcGIS Desktop 

0 Kudos
DanPatterson_Retired
MVP Emeritus

the point layer is still there, there is no cursor and the point layer is closed by the with statement.

Experiment with a large file, one that would take a second or two to process and monitor memory usage.

0 Kudos