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?
In Python 3.3 or later:
In earlier Pythons (including Python 2):