Yield from
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: yield-from
Section titled “Sourcery refactoring id: yield-from”Description:
Section titled “Description:”Replaces yield as part of for loops with yield from
Before:
Section titled “Before:”def get_content(entry): for block in entry.get_blocks(): yield blockAfter:
Section titled “After:”def get_content(entry): yield from entry.get_blocks()Explanation:
Section titled “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.