Oddity with lambda and yield

Ian Kelly ian.g.kelly at gmail.com
Thu Jan 8 09:30:11 EST 2015


On Thu, Jan 8, 2015 at 5:11 AM, Chris Angelico <rosuav at gmail.com> wrote:
> 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.

I don't see anything in PEP 380 suggesting that it shouldn't apply to
lambda functions.

>>> def f(g):
...     v = (yield from g)
...     yield v
...
>>> g = lambda: (yield 42) or (yield 43) or (yield 44) or "hello world"
>>> list(f(g()))
[42, 43, 44, None]

Seems like a bug to me.



More information about the Python-list mailing list