Oddity with lambda and yield

Chris Angelico rosuav at gmail.com
Thu Jan 8 07:11:11 EST 2015


As yield is an expression, it's legal in a lambda function, which then
means you have a generator function. But it's not quite the same as
the equivalent function made with def:

$ python3
Python 3.5.0a0 (default:1c51f1650c42+, Dec 29 2014, 02:29:06)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f=lambda: (yield 5)
>>> x=f()
>>> next(x)
5
>>> x.send(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> def f(): return (yield 5)
...
>>> x=f()
>>> next(x)
5
>>> x.send(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration: 123


Is this a bug? I very much doubt any sane code will ever run into
this; I discovered this purely by chance, after noting that
Python/compile.c had code to create a generator. The same thing
happens with Python 3.4.2 on Debian Jessie, so this isn't a bug I've
introduced in my local fiddling around.

If nothing else, it's an amusing proof that you shouldn't just stuff
every cool thing you can think of into a single line of code :)

ChrisA



More information about the Python-list mailing list