satwikkansal/wtfpython

Add section explaining 'yield' in list comp/generator exp

chris-rands opened this issue · 4 comments

These examples illustrate what for me is one of the most confusing behaviours in the whole of Python:

>>> [(yield x) for x in ('a','b')]
<generator object <listcomp> at 0x7f69d5379ba0>
>>> list([(yield x) for x in ('a','b')])
['a', 'b']
>>> list((yield x) for x in ('a','b'))
['a', None, 'b', None]

A relevant SO question and bug report

Ah, I went through the SO thread and the bug report but unfortunately couldn't come up with a simple and short explanation. So I think for the time being, it's better to link to the resources you shared. Meanwhile I'll try to come up with a simpler explanation with the help of examples.

@chris-rands Thanks for your suggestion. I've added this snippet in #45, and will try my best to add a detailed explanation for the same.

@satwikkansal Thank you for incorporating my suggestion and apologies for not responding before; I don't think I can provide a better explanation than that given in the links but it might be worth adding that this behaviour described may change because this really is a bug and not a feature. As the bug report states, for PyPy these constructs now raise a SyntaxWarning (but not for CPython).

Update: see the more recent discussion on the bug report bugs.python.org/issue10544; this syntax will sometimes raise a DeprecationWarning in Py 3.7 and then a SyntaxError from Py 3.8 docs.python.org/3.7/whatsnew/3.7.html#deprecated