77 points · by cool-RR · 14y ago · 43 comments
>>> f()
<generator object <lambda> at 0x00B50828>
Since then someone proposed (PEP 342) that yield could be used not just to yield values from coroutines, but to send one back in. yield becomes an expression, mostly used as the right side of an assignment. The parentheses are there because the grammar seems to handle the yield statement and yield expressions differently (the PEP mentions that "yield 12, 42" would have become confusing).
You can also use it inside generators:
>>> def f():
while True:
xyz = (yield)
print xyz
>>> g = f()
>>> g.next()
# nothing happens as xyz == None
>>> g.send('huhu')
huhuShort answer: it throws a syntax error otherwise.
Long answer: I don't know.
edit: typo
>>> 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
>>> >>> f=lambda: (yield)
>>> gen=f()
>>> gen.next()
>>> gen.send('foobar')
'foobar'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. );g=(int
giving: f = lambda: g();g=(int)
f() -> 0http://hamakor.org.il/pipermail/python-il/2011-December/thre...
""" >>> f = lambda: g()if 0 else(1)
>>> f()
1 >>> f = lambda: g()if 0 else()
>>> f()
()I now did a (Scroll down...) thing to "hide" the solution.
);f=(set
Leading to the whole line reading:
f = lambda: g();f=(set)
8 characters
);f=set#
8 chars
f()
technically not two commands, and it will look like:
>>> f = lambda: g(""")
. . . f()