by cool-RR · 14y ago · 0 comments
Consider this:
>>> g = lambda x: 7
>>> f = lambda: g((yield))
>>> list(f())
[None]
Can you tell me where the 7 went to? As far as I see, it went into oblivion.Python 2.6:
>>> dis.dis(f)
1 0 LOAD_GLOBAL 0 (g)
3 LOAD_CONST 0 (None)
6 YIELD_VALUE
7 CALL_FUNCTION 1
10 RETURN_VALUE
Python 2.7: >>> dis.dis(f)
1 0 LOAD_GLOBAL 0 (g)
3 LOAD_CONST 0 (None)
6 YIELD_VALUE
7 CALL_FUNCTION 1
10 POP_TOP
11 LOAD_CONST 0 (None)
14 RETURN_VALUE
In essence the Python 2.7 compiler decides to throw away the result of the g() function call and replaces it with None. Does anyone understand why?Edit: Perhaps, to clear things up more, about where the value 7 went- your snippet can be expressed without using lambdas as
>>> def g(x):
... return 7
...
>>> def f():
... v = (yield)
... g(v)
...
>>> list(f())
[None]
Note that there's no return before g(v) because generators (at least in 2.7) can only yield, not return a value.