3 ms·
Can someone explain. It would seem like g still isn't defined. What's special about 'yield' that makes g valid?
by tocomment 15y ago
Can someone explain. It would seem like g still isn't defined. What's special about 'yield' that makes g valid?
- martin_k 15y agoYou're right, it isn't. The presence of yield makes the return value of f() a generator object. The function body is not executed initially. When you call .next() on the generator object execution starts and runs until it hits the first yield, raising a NameError because g is not defined. edit: typo
- ul5255 15y agominor nit: it will not even reach the yield expression because it fails to resolve g: >>> import dis >>> f = lambda: g((yield)) >>> dis.dis(f) 1 0 LOAD_GLOBAL 0 (g) 3 LOAD_CONST 0 (None) 6 YIELD_VALUE 7 CALL_FUNCTION 1 10 RETURN_VALUE >>>