Creating an iterator in a class

Joseph L. Casale jcasale at activenetwerx.com
Thu Dec 27 20:58:42 CET 2012


> It's probably best if you use separate cursors anyway.  Say you have
> two methods with a shared cursor:
>
>     def iter_table_a(self):
>         self.cursor.execute("SELECT * FROM TABLE_A")
>         yield from self.cursor
>
>     def iter_table_b(self):
>         self.cursor.execute("SELECT * FROM TABLE_B")
>         yield from self.cursor
>
> If the client code calls iter_table_a and partially iterates over the
> result, and then needs to use iter_table_b for some reason, then when
> it gets back to the table A results the data will be gone.  You can
> only safely share cursors when you can guarantee that each query will
> be completely processed before the next query is run, and you can't
> guarantee that if you're just returning iterators.

Oops, I admit I never tested that scenario before and you are right, its
not a sane assumption.

Thanks, I'll rewrite that section.
jlc


More information about the Python-list mailing list