Skip to content

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.

Replaces yield as part of for loops with yield from

def get_content(entry):
for block in entry.get_blocks():
yield block
def get_content(entry):
yield from entry.get_blocks()

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.