OK, right off the bat: I know Python generators are lazy. That said, this is blowing my mind; I don't get it. Pythonic friends, please don't crucify me for the ignorance of this question. This was not encountered in a real-world development situation, just a curiosity that has been bothering me.
def gen1(n):
print('gen1')
return 1
def gen2(n):
print('gen2')
return 2
print(gen2(gen1(0)))
This sample does exactly what I expect it to do, it prints gen1 then gen2 then 2.
The following code sample does not:
def gen1(n):
print('gen1')
yield 1
def gen2(n):
print('gen2')
yield 2
print(list(gen2(gen1(0))))
Instead, it just prints 'gen2' and [2]. So wait a hot sec, it calls gen2 first? It never evaluates gen1? WHAT?! Under the hood, how does it pull that devil magic off? What is actually taking place here? So the outermost thing is identified as a generator and it triggers some introspections that identifies that evaluation of the inner generator is unnecessary? What is a more informative way of tracing this behavior?