473,404 Members | 2,195 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,404 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 1743
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.