2

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jaron Tang
  • 23
  • 4
  • 2
    Indeed, the `try..except` can safely be removed. It is pointless here. – Martijn Pieters Sep 18 '15 at 09:06
  • Seems to be useless here, but you should specify what exactly read_line does or how it will behave when the iterator is exhausted. – dorvak Sep 18 '15 at 09:09
  • 1
    @dorvak: This is from the free O'Reilly ebook [*Functional programming in Python*](http://www.oreilly.com/programming/free/functional-programming-python.csp), and David does not share the implementation in that book. Even worse, between different examples, it switches from an iterator to a `next()`-like function, two very different implementations. – Martijn Pieters Sep 18 '15 at 12:39

2 Answers2

3

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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.

Paul Becotte
  • 9,767
  • 3
  • 34
  • 42