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

Barry Warsaw barry at python.org
Mon Nov 7 16:40:34 CET 2011


On Nov 06, 2011, at 05:52 PM, Guido van Rossum 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.
>
>I'm not sure that it's still that important -- in fact I'm not sure Python
>3 still has this behavior.

I did some performance testing back when this was introduced.  They numbers
aren't relevant any more, but the basic idea was to time things like
dictionary access with .get() vs. __getitem__() both when the key was in the
dictionary and when it was missing.  There were some other timing tests IIRC.
IIRC, instantiating the exception in every case was a fairly significant hit.

It would be good to see some updated tests and numbers before anything was
changed in the interpreter.

-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111107/2d027078/attachment.pgp>


More information about the Python-ideas mailing list