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)
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.