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

Guido van Rossum guido at python.org
Mon Nov 7 02:52:14 CET 2011


On Sun, Nov 6, 2011 at 5:46 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Mon, Nov 7, 2011 at 11:38 AM, Gregory P. Smith <greg at krypto.org> wrote:
> >
> > On Tue, Nov 1, 2011 at 1:15 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> >>
> >> No, the traceback info is added by the eval loop itself. Remember that
> >> when you raise an exception *type* (rather than an instance), the
> >> exception doesn't get instantiated until it gets caught somewhere -
> >> the eval loop maintains the unwinding stack for the traceback as part
> >> of the thread state until it is time to attach it to the exception
> >> object.
> >
> > I did not know that.  Is there a good reason for doing this?  It seems
> > unnecessarily complicated.
>
> You'll have to ask Guido that one - it's been like that since long
> before I got involved in hacking on the interpreter.
>
> It's possibly a lingering artifact of the old "exceptions are just
> strings" design, since traceback storage didn't get added to exception
> instances until Py3k.
>

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.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111106/292b82c6/attachment.html>


More information about the Python-ideas mailing list