<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On 25 January 2017 at 07:01, Chris Angelico <span dir="ltr"><<a href="mailto:rosuav@gmail.com" target="_blank">rosuav@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><span class="gmail-">
>>> [(yield 1) for x in range(10)]<br>
> <generator object <listcomp> at 0x10cd210f8></span><br></blockquote><div><br><div><div>This is an old bug, see e.g. <a href="http://bugs.python.org/issue10544">http://bugs.python.org/issue10544</a><br></div>The ``yield`` inside comprehensions is bound to the auxiliary function.<br>Instead it should be bound to an enclosing function, like it is done for ``await``.<br></div><div>The behaviour of ``await`` in comprehensions is intuitive<br>(since it is simply equivalent to a for-loop):<br><br>>>> async def f(i):<br>... return i<br><br>>>> async def g_for():<br>... lst = []<br>... for i in range(5):<br>... lst.append(await f(i))<br>... print(lst)<br><br>>>> g_for().send(None)<br>[0, 1, 2, 3, 4]<br>Traceback (most recent call last):<br> File "<stdin>", line 1, in <module><br>StopIteration<br><br>>>> async def g_comp():<br>... print([await f(i) for i in range(5)])<br><br>>>> g_comp().send(None) # exactly the same as g_for<br>[0, 1, 2, 3, 4]<br>Traceback (most recent call last):<br> File "<stdin>", line 1, in <module><br>StopIteration<br><br>While current behaviour of ``yield`` in comprehensions is confusing:<br><br>>>> def c_for():<br>... lst = []<br>... for i in range(5):<br>... lst.append((yield i))<br>... print(lst)<br><br>>>> c_for().send(None)<br>0<br>>>> c_for().send(None)<br>1<br></div><div># etc.<br></div><div><br>>>> def c_comp():<br>... print([(yield i) for i in range(5)])<br><br>>>> c_comp().send(None) # Naively this should be equivalent to the above, but...<br><generator object c_comp.<locals>.<listcomp> at 0x7f1fd1faa630><br>Traceback (most recent call last):<br> File "<stdin>", line 1, in <module><br>AttributeError: 'NoneType' object has no attribute 'send'<br><br></div><div></div>I promised myself to write a patch, but didn't have time for this yet.<br></div><div>I hope I will do this at some point soon.<br><br>--<br></div><div>Ivan<br><br><br></div></div></div></div>