Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Creating an iterator in a class (http://www.velocityreviews.com/forums/t955867-re-creating-an-iterator-in-a-class.html)

Ian Kelly 12-27-2012 06:35 PM

Re: Creating an iterator in a class
 
On Thu, Dec 27, 2012 at 7:44 AM, Joseph L. Casale
<jcasale@activenetwerx.com> wrote:
> I am writing a class to provide a db backed configuration for an application.
>
> In my programs code, I import the class and pass the ODBC params to the
> class for its __init__ to instantiate a connection.
>
> I would like to create a function to generically access a table and provide an
> iterator. How does one create a function in a class that takes an argument and
> returns an iterator? I saw some examples where the class gets instantiated
> with the table defined but I was hoping not to do this so I could continue to
> access various tables through one connection/cursor.


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.


All times are GMT. The time now is 03:33 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.