我在阅读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)
最佳答案
我认为没有任何理由将try... except
保留在那里。例如,重新加注仍将带有相同的回溯,因此生成器的行为不会改变。
换句话说,它在那里毫无意义,可能是重构留下的产物。
您可以进一步简化循环,删除多余的第一行:
def get_log_lines(log_file):
while True:
line = read_line(log_file)
if complex_condition(line):
yield line
关于python - Python 中的停止迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648006/