python - Python 生成器函数中的代码重复

标签 python generator

过程式编程的优点之一是能够将任何代码提取到函数中,该函数可以在许多地方重用,从而减少代码重复。然而Python中的yield语句似乎削弱了这种能力,因为当yield语句被提取到另一个函数中时,原来的生成器函数就变成了普通的生成器函数,从而无法不再用作发电机。

考虑这个例子:

def foo():
  do_something()
  bar = get_some_value()
  yield bar
  save(bar)
  do_something_else()
  # more code in between
  bar = get_some_value()
  yield bar
  save(bar)
  # finishing up

请注意,yield 语句周围的代码始终相同,但我们无法将其提取到函数中。

这是 Python 的已知缺陷还是有解决方法可以重用 yield 语句周围的代码?

最佳答案

在 Python 3.3 或更高版本中:

def helper():
    bar = get_some_value()
    yield bar
    save(bar)

def foo():
  do_something()
  yield from helper()
  do_something_else()
  # more code in between
  yield from helper()
  # finishing up

在早期的 Python(包括 Python 2)中:

def helper():
    bar = get_some_value()
    yield bar
    save(bar)

def foo():
  do_something()
  for x in helper(): yield x
  do_something_else()
  # more code in between
  for x in helper(): yield x
  # finishing up

关于python - Python 生成器函数中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970302/

相关文章:

python - 如何从外部有效 XML 标记中删除垃圾?

python - Python 中的并行.For

python - 使用 GEKKO 进行快速傅立叶变换

python - 将格式化控制字符(退格和回车)应用于字符串,无需递归

python - 如何在python中读取其他目录中的文件

python - 将带有回调的函数转换为 Python 生成器?

生成器的 python 生成器?

javascript - 从生成器传播 yield ,同时以相同的方式使用它们(重用)

python,生成器迭代一个或多个项目

javascript - ES6 生成器机制 - 传递给 next() 的第一个值去哪里了?