Jaron Tang
Jaron Tang

Reputation: 23

StopIteration in Python

I encounter a problem while reading functional programming python.

def get_log_lines(log_file): 
    line = read_line(log_file) 
    while True:
        try:
            if complex_condition(line):
                yield line
            line = read_line(log_file)
        except StopIteration:
            raise

A try...except statement is added to surround the read_line. Why not just let read_line throw the StopIteration exception like this:

def get_log_lines(log_file): 
    line = read_line(log_file) 
    while True:
        if complex_condition(line):
            yield line
        line = read_line(log_file)

Upvotes: 2

Views: 2097

Answers (2)

Paul Becotte
Paul Becotte

Reputation: 9977

The author was writing an example. While the try...catch block doesn't actually do anything here, he probably included it so that you could SEE how the loop would get broken.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121644

I don't think there is any reason to keep the try...except there. The re-raise will still carry the same traceback, for example, so the behaviour of the generator is unchanged with it there.

In other words, it is pointless there, perhaps a left-over artefact of a refactoring.

You can simplify the loop even further, removing the redundant first line:

def get_log_lines(log_file): 
    while True:
        line = read_line(log_file) 
        if complex_condition(line):
            yield line

Upvotes: 3

Related Questions