Code duplication in generator functions in Python

80 Views Asked by At

One of the advantage of procedural programming is the ability to extract any piece of code into a function, which could be reused in many places, reducing code duplication. However, the yield statement in Python seems to reduce this ability, because when yield statement is extracted into another function, the original generator function becomes a normal one, and thus cannot be used as a generator anymore.

Consider this example:

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

Note that the code around yield statements is always the same, but we can't extract it to a function.

Is this a known deficiency of Python or is there a workaround to reuse the code around yield statements?

1

There are 1 best solutions below

0
On BEST ANSWER

In Python 3.3 or later:

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

In earlier Pythons (including 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