More pythonic way to iterate
Posted
by fmark
on Stack Overflow
See other posts from Stack Overflow
or by fmark
Published on 2010-06-05T10:48:42Z
Indexed on
2010/06/05
10:52 UTC
Read the original article
Hit count: 390
I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic.
To iterate over rows, the follwoing syntax is used:
cursor = gp.getcursor(table)
row = cursor.Next()
while row:
#do something with row
row = cursor.next()
What is the most pythonic way to deal with this situation? I have considered creating a first class function/generator and wrapping calls to a for loop in it:
def cursor_iterator(cursor):
row = cursor.Next()
while row:
yield row
row = cursor.next()
[...]
cursor = gp.getcursor(table)
for row in cursor_iterator(cursor):
# do something with row
This is an improvement, but feels a little clumsy. Is there a more pythonic approach? Should I create a wrapper class around the table
type?
© Stack Overflow or respective owner