Basic misunderstanding of generators

David Stanek dstanek at dstanek.com
Mon Dec 22 10:27:49 EST 2008


On Mon, Dec 22, 2008 at 4:47 AM, Barak, Ron <Ron.Barak at lsi.com> wrote:
>
> if __name__ == "__main__":
>     filename = "sac.log.gz"
>     log_stream = LogStream(filename)
>     line_ = log_stream.next_line(log_stream.input_file)
>     print line_
>
> $ python LogManager_try.py
> <generator object at 0x00B94648>
>

A method or function containing a yield statement will return a
generator instance when called. Which is what is happening in your
example.

What you want to do is something like:

for line in log_stream.next_line(log_stream.input_file):
   print line

To make the code bit simpler and more OO you should not need to pass
anything into next_line(). It is a part the object so it naturally has
access to its properties. That being said you can then use __iter__
instead and then you can then do something like:

for line in log_stream:
  print line

OTOH If your LogStreamer class doesn't keep any additional state I
would probably just create a single generator function.

-- 
David
http://www.traceback.org



More information about the Python-list mailing list