generator_closure.py 697 B

1234567891011121314151617181920212223242526272829303132
  1. # a generator that closes over outer variables
  2. def f():
  3. x = 1 # closed over by g
  4. def g():
  5. yield x
  6. yield x + 1
  7. return g()
  8. for i in f():
  9. print(i)
  10. # a generator that has its variables closed over
  11. def f():
  12. x = 1 # closed over by g
  13. def g():
  14. return x + 1
  15. yield g()
  16. x = 2
  17. yield g()
  18. for i in f():
  19. print(i)
  20. # using comprehensions, the inner generator closes over y
  21. generator_of_generators = (((x, y) for x in range(2)) for y in range(3))
  22. for i in generator_of_generators:
  23. for j in i:
  24. print(j)
  25. # test that printing of closed-over generators doesn't lead to segfaults
  26. def genc():
  27. foo = 1
  28. repr(lambda: (yield foo))
  29. genc()