[Python-Dev] patch: try/finally in generators

Neil Schemenauer nas@python.ca
Mon, 29 Jul 2002 13:25:15 -0700


Guido van Rossum wrote:
> I'd also like to get Neil Schemenauer's review of the code, since he
> knows best how generators work under the covers.

I'm pretty sure it can be made to work (at least for CPython).  The
proposed patch is not correct since it doesn't handle "finally" code
that creates a new reference to the generator.  Also, setting the
instruction pointer to the return statement is really ugly, IMO.  There
could be valid code out there that does not end with LOAD_CONST+RETURN.

Those are minor details though.  We need to decide if we really want
this.  For example, what happens if 'yield' is inside the finally block?
With the proposed patch:

    >>> def f():
    ...   try:
    ...     assert 0
    ...   finally:
    ...     return 1
    ... 
    >>> f()
    1
    >>> def g():
    ...   try:
    ...     assert 0
    ...   finally:
    ...     yield 1
    ... 
    >>> list(g())
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 3, in g
    AssertionError

Maybe some people whould expect [1] in the second case.

  Neil