2

我在阅读函数式编程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

添加了一个try...except语句来包围read_line. 为什么不让read_line抛出这样的StopIteration异常:

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

2 回答 2

3

我认为没有任何理由保留try...except那里。例如,重新加注仍将带有相同的回溯,因此生成器的行为在那里没有改变。

换句话说,它在那里毫无意义,也许是重构的遗留产物。

您可以进一步简化循环,删除多余的第一行:

def get_log_lines(log_file): 
    while True:
        line = read_line(log_file) 
        if complex_condition(line):
            yield line
于 2015-09-18T09:08:25.857 回答
0

作者正在写一个例子。虽然 try...catch 块在这里实际上并没有做任何事情,但他可能将它包含在内,以便您可以看到循环是如何被破坏的。

于 2015-09-18T11:40:22.597 回答