[Python-Dev] GeneratorExit inheriting from Exception

Guido van Rossum guido at python.org
Sat Mar 25 16:43:17 CET 2006


On 3/25/06, Nick Coghlan <ncoghlan at gmail.com> wrote:
> The last comment I heard from Guido on this topic was that he was still
> thinking about it.

Not exactly. I'm delegating the thinking mostly to others.

> However, I now have an additional data point - if GeneratorExit inherits
> directly from BaseException, it makes it much easier to write exception
> handling code in generators that does the right thing on both Python 2.4 and 2.5.
>
> In 2.4, PEP 342 hasn't happened, so "except Exception:" can't misbehave in
> response to GeneratorExit (the latter doesn't exist, and nor does generator
> finalisation). If GeneratorExit inherits directly from BaseException, the code
> still does the right thing since the exception isn't caught.
>
> OTOH, if GeneratorExit inherits from Exception (as in current SVN), then two
> things will be needed to make the generator work correctly:
>
> 1. add a preceding exception clause to fix Python 2.5 behaviour:
>    except GeneratorExit:
>        raise
>    except Exception:
>        # whatever
>
> 2. add header code to the module to make it work again on Python 2.4:
>
>    try:
>        GeneratorExit
>    except NameError:
>        class GeneratorExit(Exception): pass
>
> IMO, that would be an ugly bit of backwards incompatibility (even though I
> wouldn't expect such broad exception handling in generators to be at all common).

I can't see all that much use for GeneratorExit in code that needs to
be compatible with 2.4, since the rest of the machinery that makes
exception handling around yield feasible doesn't exist.

Rather than speaking of "data points" which are really just "ideas",
try to come up with a data point that represents an actual (not
made-up) use case to show the difference.

I'm saying this because, while I believe there *may* be something
here, I also believe that the decision to derive an exception from
BaseException instead of Exception should not be taken lightly -- lest
we set the wrong example and render the nice feature we're trying to
create (that "except Exception"does the right thing almost all of the
time) useless.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list