Creating an iterator in a class

Peter Otten __peter__ at web.de
Thu Dec 27 10:14:52 EST 2012


Joseph L. Casale 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.

Have the method yield instead of returning:

>>> class Names:
...     def __init__(self, template):
...             self.template = template
...     def generate_names(self, upto):
...             for index in range(1, upto+1):
...                     yield self.template.format(index)
... 
>>> names = Names("file{}.txt")
>>> for name in names.generate_names(3):
...     print name
... 
file1.txt
file2.txt
file3.txt
>>> list(names.generate_names(2))
['file1.txt', 'file2.txt']
>>> g = names.generate_names(3)
>>> next(g)
'file1.txt'
>>> next(g)
'file2.txt'
>>> next(g)
'file3.txt'
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration





More information about the Python-list mailing list