Yield in for ... in

Viewed 77

I came across some code like this:

def func(tree):
 nodes = tree
 for node in nodes:
  yield node
  nodes += [42]

gen = func([-42, 3, 1, 4, 159])

for i in range(10):
 print(next(gen))

Does this code have undefined behaviour?

Specifically, does:

for node in nodes:
 yield node
 nodes += [42]

show undefined behviour?

I know that:

for node in nodes:
 # yield node
 nodes += [42]

may cause unexpected behaviour because the variable we are iterating through (nodes) is being updated in the for loop.

1 Answers

No, why would the behavior be undefined?

The generator yields all original elements from the tree argument and then 42 to infinity.

>>> gen = func([1, 2, 3])
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
3
>>> next(gen)
42
>>> next(gen)
42
>>> next(gen)
42

Extending nodes with [42] for each yield makes sure that the generator will never run out of numbers to yield.

The only problem is that if you call next enough times you will encounter a MemoryError because nodes grew too large.

Related