Yield from¶
Sourcery refactoring id: yield-from
¶
Description:¶
Replaces yield
as part of for
loops with yield from
Before:¶
def get_content(entry):
for block in entry.get_blocks():
yield block
After:¶
def get_content(entry):
yield from entry.get_blocks()
Explanation:¶
One little trick that often gets missed is that Python's yield
keyword has a
corresponding yield from
for collections, so there's no need to iterate over a
collection with a for loop. This makes the code slightly shorter and removes the
mental overhead and extra variable used by the for loop. Eliminating the for
loop also makes the yield from
version about 15% faster.
Note that this cannot be done on async
functions.