Skip to content

Instantly share code, notes, and snippets.

@tomislacker
Last active July 15, 2019 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomislacker/da3e474f5b06f0e47cb3b4ec4f18e6c0 to your computer and use it in GitHub Desktop.
Save tomislacker/da3e474f5b06f0e47cb3b4ec4f18e6c0 to your computer and use it in GitHub Desktop.
Python Nested Generators with `yield from` Syntax (>=Python.3.3)

TIL about the yield from syntax introduced in >=Python-3.3

In [6]: def f1(p): 
   ...:     yield f'{p}1' 
   ...:     yield f'{p}2' 
   ...:      
   ...:                                                                         

In [7]: def f2(): 
   ...:     yield 'a' 
   ...:     yield 'b' 
   ...:                                                                         

In [8]: def f3(): 
   ...:     for p1 in f2(): 
   ...:         yield from f1(p1) 
   ...:                                                                         

In [9]: list(f3())                                                              
Out[9]: ['a1', 'a2', 'b1', 'b2']

MOAR NESTING

Code

#!/usr/bin/env python
from __future__ import print_function


def f1(p):
    yield f'{p}1'
    yield f'{p}2'

def f2():
    yield 'a'
    yield 'b'

def f3(p):
    for p1 in f2():
        yield from f1(f'{p}-{p1}')


def f_final():
    for p2 in f2():
        yield from f3(p2)


if __name__ == '__main__':
    full = list(f_final())
    print(f'Found {len(full)} elements')
    for i, v in enumerate(full):
        print(f'[{i}]: "{v}"')

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

Output

Found 8 elements
[0]: "a-a1"
[1]: "a-a2"
[2]: "a-b1"
[3]: "a-b2"
[4]: "b-a1"
[5]: "b-a2"
[6]: "b-b1"
[7]: "b-b2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment