[Python-ideas] thoughts on generator.throw()

Nick Coghlan ncoghlan at gmail.com
Wed Mar 18 23:30:56 CET 2009

Gerald Britton wrote:
> Today I was reviewing changes in Python 2.5 and I noticed the
> generator throw() method for the first time.  While thinking about
> what it does and why, a question arose in my mind:
> Why is it called "throw"?  (Yes, I know that Java and possibly other
> languages use this keyword!)  In Python, we have long had a "raise"
> statement to raise exceptions.  I would have thought that the
> generator method would have been called "raise" as well.  But then I
> saw that it would have been impossible to implement since "raise" is a
> Python keyword.

Actually, it was also called throw because it says "raise this exception
over *there* (i.e inside the generator)". We're throwing the exception
"over the fence" as it were. That was a rationalisation of a necessity
(see the description in PEP 342), but still a good idea.

>  *Then* I wondered why "raise" is a keyword and not a
> function.

Because the compiler needs to see it and insert the appropriate commands
into the bytecode to tell the interpreter to find the nearest exception
handler or finally block and resume execution there.

While you could probably figure out a way to do that without dedicated
bytecode, I doubt it would do good things to the structure of the eval loop.

> I have a similar question about the "assert" statement.  It could
> possibly benefit from being a function instead. Of course, changing
> this would break lots of code, but maybe not any more than making
> print a function as in 3.0.

As others have said, so the compiler can drop it when optimisation is
switched on.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list