Nick Coghlan wrote:
Carl Johnson wrote:
Certainly, it's an inconsistency compared to generator expressions, but is it a bug? I know that Python 3000 is making it so that list comprehension variables don't leak anymore, so I take it that the goal is to have them be more similar to generator expressions than not. Then again, maybe there are good reasons for this behavior? My own feeling is that these two cases should behave the same way, but I could be wrong.

Comprehensions and generator expressions in Py3k are more similar than they are in 2.x, but they still aren't identical.

[x for x in range(10) if f(x)] is shorthand for:

  def _f(itr):
      _[1] = []
      for x in itr:
          if f(x):
              _[1].append(x)
      return _[1]
  expr_result = _f(range(10))

While (x for x in range(10) if f(x)) is shorthand for:

  def _g(itr):
      for x in itr:
          if f(x):
              yield x
  expr_result = _g(range(10))

From those expansions, I think it's pretty clear that the implicit generator function in the second case is going to swallow the StopIteration and treat it as the end of the iteration process, but no such thing is going to happen with the implicit standard function in the list comprehension case.

The idea I had, and which is what I believe Adam Olsen posted, is to augment the genexp to
   def _g(itr):
     try:
       for x in itr:
           if f(x):
               yield x
     except StopIteration: # possibly add 'as si'
       raise RuntimeError(<msg>) # <msg> might incorporate si msg

To me, it is more important that list(genexp) == corresponding_listcomp than that the definition of genexp be minimal.

tjr

_______________________________________________
Python-3000 mailing list
Python-3000@python.org
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to