[Python-Dev] Tricky way of of creating a generator via a comprehension expression

Guido van Rossum guido at python.org
Thu Nov 23 11:08:03 EST 2017


This thread is still going over the speed limit. Don't commit anything
without my explicit approval.

I know one thing for sure. The choice to make all comprehensions functions
was quite intentional (even though alternatives were also discussed) and
the extra scope is now part of the language definition. It can't be removed
as a "bug fix". One thing that can be done without a PEP is making yield
inside a comprehension a syntax error, since I don't think *that* was
considered when the function scopes were introduced.

A problem with dropping the "function-ness" of the comprehension by
renaming the variables (as Ivan/Serhiy's plan seems to be?) would be what
does it look like in the debugger -- can I still step through the loop and
print the values of expressions? Or do I have to know the "renamed" names?

And my mind boggles when considering a generator expression containing
yield that is returned from a function. I tried this and cannot say I
expected the outcome:

  def f():
      return ((yield i) for i in range(3))
  print(list(f()))

In both Python 2 and Python 3 this prints

  [0, None, 1, None, 2, None]

Even if there's a totally logical explanation for that, I still don't like
it, and I think yield in a comprehension should be banned. From this it
follows that we should also simply ban yield  from comprehensions.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20171123/0a33c1ca/attachment.html>


More information about the Python-Dev mailing list