[Python-ideas] raising an exception type doesn't instantiate it until it gets caught

Nick Coghlan ncoghlan at gmail.com
Mon Nov 7 03:03:46 CET 2011


On Mon, Nov 7, 2011 at 11:52 AM, Guido van Rossum <guido at python.org> wrote:
> No, it was actually introduced when exceptions became classes. It is an
> optimization that we deemed important at the time: to avoid instantiating
> the class when it's going to be caught by C code that doesn't care about the
> instance. A common example is StopIteration, but there are probably plenty
> of other situations like it. We may even have benchmarked for-loops with and
> without this -- while the exception only happens once per for-loop, there
> are a lot of for-loops, many of which iterate over small sequences, and it
> adds up.

Ah, thanks - interesting to know.

> I'm not sure that it's still that important -- in fact I'm not sure Python 3
> still has this behavior.

I'm fairly sure it does (it was the 3.x version of ceval that I was
reading to remind myself of how the stack unwinding process actually
works and the call to PyErr_NormalizeException() is still in there).
It's just that without the multiple argument forms of the raise
statement, pure Python code can only exploit it for exceptions without
any arguments (so it still works for the StopIteration optimisation).

Cheers,
Nick.

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



More information about the Python-ideas mailing list