473,396 Members | 1,894 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

exception raised by nested iterator being ignored by for loop

I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop. Wrapping the second for loop in a try/except clause
shows that the exception is being raised though.

Could someone more familiar with the underlying implementation please
give me a hint as to why this is happening?
import gzip
class wrapper :

def __init__ (self, filename) :
if filename[-3:] == ".gz" :
self.fh = gzip.GzipFile(filename, "r")
else :
self.fh = open(filename, "r")

def __iter__ (self) :
return self

def next (self) :
for line in self.fh : # StopIteration raised here when
file exhausted
if line[:1] == "t" : # filter out lines starting with
't'
continue
return line.rstrip()

if __name__ == "__main__" :
# using the file handle
fh = open("test.txt")
for line in fh :
print line.rstrip()
fh.close()

# using the wrapper class
fh = wrapper("test.txt")
for line in fh : # StopIteration ignored here
print line

Nov 22 '05 #1
4 1741
james t kirk wrote:
I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop.


Admiral Kirk,

The innermost for-loop is catching its own StopIteration. You need to
explicitly raise StopIteration in your next() method when there are no
more lines in the file (hint, add an else-clause to the for-loop).

Alternatively, you could simplify your life by writing the whole
wrapper as a generator:
import gzip

def wrapper(filename) :
if filename[-3:] == ".gz" :
fh = gzip.GzipFile(filename, "r")
else :
fh = open(filename, "r")
for line in fh:
if line[:1] != "t": # filter out lines starting with 't'
yield line.rstrip()
fh.close()
Raymond Hettinger
Starfleet Command

Nov 22 '05 #2
james t kirk wrote:
I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop.


Admiral Kirk,

The innermost for-loop is catching its own StopIteration. You need to
explicitly raise StopIteration in your next() method when there are no
more lines in the file (hint, add an else-clause to the for-loop).

Alternatively, you could simplify your life by writing the whole
wrapper as a generator:
import gzip

def wrapper(filename) :
if filename[-3:] == ".gz" :
fh = gzip.GzipFile(filename, "r")
else :
fh = open(filename, "r")
for line in fh:
if line[:1] != "t": # filter out lines starting with 't'
yield line.rstrip()
fh.close()
Raymond Hettinger
Starfleet Command

Nov 22 '05 #3
On Sun, 20 Nov 2005 03:36:43 GMT, james t kirk <ja**********@ussenterprise.com> wrote:
I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop. Wrapping the second for loop in a try/except clause
shows that the exception is being raised though.

Could someone more familiar with the underlying implementation please
give me a hint as to why this is happening?

import gzip
class wrapper :

def __init__ (self, filename) :
if filename[-3:] == ".gz" :
self.fh = gzip.GzipFile(filename, "r")
else :
self.fh = open(filename, "r")

def __iter__ (self) :
return self

def next (self) :
for line in self.fh : # StopIteration raised here when
file exhausted Yes, but that just ends the for loop and that uses up the exception, so either
change the above "for ..." to two lines: (untested ;-/ )
while True:
line = self.fh.next() # should raise StopIteration without
# being caught by for if line[:1] == "t" : # filter out lines starting with
't'
continue
return line.rstrip() or otherwise the end of the for will catch the StopIteration and just drop out here.
Imagine you were just printing the line in the loop body instead of checking and
returning lines. With just a print, you wouldn't expect a StopIteration to escape the for loop, right?
If you want to leave the for unchanged, you could just tell the world that the wrapper iteration
is done, by using the following line here:
raise StopIteration # end of wrapper iteration

if __name__ == "__main__" :
# using the file handle
fh = open("test.txt")
for line in fh :
print line.rstrip()
fh.close()

# using the wrapper class
fh = wrapper("test.txt")
for line in fh : # StopIteration ignored here
print line


HTH (and that the untested code works ;-)

Regards,
Bengt Richter
Nov 22 '05 #4
On Sun, 20 Nov 2005 03:36:43 GMT, james t kirk <ja**********@ussenterprise.com> wrote:
I'm writing a wrapper class to handle the line merging and filtering
for a log file analysis app

The problem I'm running into is that the StopIteration exception
raised when the wrapped file goes past EOF isn't causing the second
for loop to stop. Wrapping the second for loop in a try/except clause
shows that the exception is being raised though.

Could someone more familiar with the underlying implementation please
give me a hint as to why this is happening?

import gzip
class wrapper :

def __init__ (self, filename) :
if filename[-3:] == ".gz" :
self.fh = gzip.GzipFile(filename, "r")
else :
self.fh = open(filename, "r")

def __iter__ (self) :
return self

def next (self) :
for line in self.fh : # StopIteration raised here when
file exhausted Yes, but that just ends the for loop and that uses up the exception, so either
change the above "for ..." to two lines: (untested ;-/ )
while True:
line = self.fh.next() # should raise StopIteration without
# being caught by for if line[:1] == "t" : # filter out lines starting with
't'
continue
return line.rstrip() or otherwise the end of the for will catch the StopIteration and just drop out here.
Imagine you were just printing the line in the loop body instead of checking and
returning lines. With just a print, you wouldn't expect a StopIteration to escape the for loop, right?
If you want to leave the for unchanged, you could just tell the world that the wrapper iteration
is done, by using the following line here:
raise StopIteration # end of wrapper iteration

if __name__ == "__main__" :
# using the file handle
fh = open("test.txt")
for line in fh :
print line.rstrip()
fh.close()

# using the wrapper class
fh = wrapper("test.txt")
for line in fh : # StopIteration ignored here
print line


HTH (and that the untested code works ;-)

Regards,
Bengt Richter
Nov 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Lonnie Princehouse | last post by:
In a recent post, Michele Simionato asked about resumable (or re-entrant) exceptions, the basic idea being that when raised and uncaught, these exceptions would only propagate backwards through a...
8
by: leo | last post by:
Hello all - I was wondering about the performance implications of explicitly raising exceptions to get information about the current frame. Something like what the inspect module does, with: ...
28
by: dcrespo | last post by:
Hi all, How can I get a raised exception from other thread that is in an imported module? For example: --------------- programA.py ---------------
0
by: james t kirk | last post by:
I'm writing a wrapper class to handle the line merging and filtering for a log file analysis app The problem I'm running into is that the StopIteration exception raised when the wrapped file...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.