More python way of iteration

I use a module that is part of the commercial software API. The good news is the python module - the bad news is that it's pretty fearless.

The following syntax is used to iterate through the lines:

cursor = gp.getcursor(table)
row =  cursor.next()
while row:
    #do something with row
    row = cursor.next()

What is the most pythonic way to handle this situation? I looked at creating a first class function / generator and wrapping calls in a for loop:

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 it feels a little awkward. Is there a more pythonic approach? Should I create a wrapper class around the type table?

+3
source share
3 answers

, Next next , , iter:

for row in iter(cursor.next, None):
    <do something>
+11

, :

class Table(object):
    def __init__(self, gp, table):
        self.gp = gp
        self.table = table
        self.cursor = None

   def __iter__(self):
        self.cursor = self.gp.getcursor(self.table)
        return self

   def next(self):
        n = self.cursor.next()
        if not n:
             raise StopIteration()
        return n

:

for row in Table(gp, table)

:

+2

The best way is to use the Python iterator interface around the object table, imho:

class Table(object):
    def __init__(self, table):
         self.table = table

    def rows(self):
        cursor = gp.get_cursor(self.table)
        row =  cursor.Next()
        while row:
            yield row
            row = cursor.next()

Now you just call:

my_table = Table(t)
for row in my_table.rows():
     # do stuff with row

It is very readable, in my opinion.

+1
source

Source: https://habr.com/ru/post/1748653/


All Articles