[Python-ideas] PEP 479: Change StopIteration handling inside generators

Terry Reedy tjreedy at udel.edu
Tue Nov 18 23:54:57 CET 2014


On 11/18/2014 12:40 PM, Wolfgang Maier wrote:

> I just remembered one use of the current behavior. Two years ago or so,
> I was suggesting on this list a possibility for early termination of
> comprehensions when a particular value is encountered. In other words,
> an equivalent to:
>
> l = []
> for x in seq:
>      if x == y:
>          break
>      l.append(x)

I believe I thought then that one should write the explicit loop rather 
than overload the 'comprehension' concept.

> At the time, somebody suggested (roughly):
>
> def stop():
>      raise StopIteration
>
> l = list(x for x in seq if x!=y or stop())

If stop is defined in another file, such as 'utility', this is a bit 
nasty.  A new maintainer comes along and changes that to a list 
comprehension, or perhaps decides a set rather than a list is needed, 
and changes it to a set comprehension instead of set() call and bingo!, 
a bug.  Or someone imitates the pattern, but with [] instead of list.

> which, for the very reasons discussed in this thread, works only as a
> generator expression and not in comprehension form.

With this example, where the StopIteration source could be much more 
obscure than next(), I now understand Guido's concern about 
hard-to-understand bugs.  From a maintainability view, it should not 
matter if one calls a function on a naked comprehension (making it a 
genexp) or uses the

> I used this solution in some not particularly important piece of code so
> I wouldn't despair if it wasn't compatible with the next release of the
> language.
> Also, I have a feeling that some of you may consider this sort of a hack
> in the first place.


-- 
Terry Jan Reedy



More information about the Python-ideas mailing list
  翻译: