Elegantly subsplitting a sequence

martin z pxtl at hotmail.com
Fri May 30 19:21:52 EDT 2003


from http://www.python.org/doc/current/ref/yield.html

The yield statement is not allowed in the try clause of a try ... finally
construct. The difficulty is that there's no guarantee the generator will
ever be resumed, hence no guarantee that the finally block will ever get
executed.

is this false?  You use it in such a structure.

"Steven Taschuk" <staschuk at telusplanet.net> wrote in message
news:mailman.1054323287.5045.python-list at python.org...
> Quoth I:
>   [...]
> >     def subsplit(iterable, groupsize=1):
> >         it = iter(iterable)
> >         try:
> >             while True:
> >                 portion = []
> >                 for _ in range(groupsize):
> >                     portion.append(it.next())
> >                 yield tuple(portion)
> >         finally:
> >             if portion:
> >                 yield tuple(portion)
> >
> > might be preferable.
>
> Heh.  Except that that code won't compile.  Fixed:
>
>     def subsplit(iterable, groupsize=1):
>         it = iter(iterable)
>         while True:
>             portion = []
>             try:
>                 for _ in range(groupsize):
>                     portion.append(it.next())
>             finally:
>                 if portion:
>                     yield tuple(portion)
>
> -- 
> Steven Taschuk                               staschuk at telusplanet.net
> "What I find most baffling about that song is that it was not a hit."
>                                           -- Tony Dylan Davis (CKUA)
>






More information about the Python-list mailing list