List comprehension with statement using arcpy.da cursors?

5004
2
Jump to solution
08-10-2012 10:29 AM
ChrisSnyder
Regular Contributor III
Excited to get my hands dirty using the arcpy.da module, and I appreciate the reasoning for the optional "with" statement syntax.

Question:

While it is possible to do this:

tileList = [r[0] for r in arcpy.da.SearchCursor(freq1Tbl, "TILE_NO")]
it doesn't seem possible to do this:
tileList = [row[0] for row in cursor with arcpy.da.SearchCursor(freq1Tbl, "TILE_NO") as cursor]


Am I using the wrong syntax here, or can you just not use the with statement in a list/dictionary comprehension?
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JasonScheirer
Occasional Contributor III
The with statement does not work in a list comprehension, no. There's no need for it assuming the comprehension does not throw an exception, though. Once a da cursor runs out of rows it closes itself in the same manner as it would leaving a with block.

View solution in original post

0 Kudos
2 Replies
JasonScheirer
Occasional Contributor III
The with statement does not work in a list comprehension, no. There's no need for it assuming the comprehension does not throw an exception, though. Once a da cursor runs out of rows it closes itself in the same manner as it would leaving a with block.
0 Kudos
ChrisSnyder
Regular Contributor III
Thanks Jason... In the docs I saw the part about the with statement "guarantee close and release of database locks and reset iteration", and thought that sounded good, but as long as the cursor executes successfully I guess that does that anyway.
0 Kudos