Raising objects

Steven Taschuk staschuk at telusplanet.net
Fri May 2 13:01:36 EDT 2003


Quoth Michael Chermside:
  [lazy exception creation]
> Steven Taschuk replies:
> > That's an interesting idea.  But I'm not sure the performance
> > advantage (if there is one) is worth the weirdness.
  [...]
> Hmmm. I was not SUGGESTING this behavior, I thought that it
> already EXISTED. [...]

Ah.  My mistake.

> [...] Let me try it out: [...]
> Okay... seems like it creates the object. In that case, I
> strongly object to this idea... better to just create the
> object every time (it's an optimization that we don't need!).

Agreed.

> Still, I wonder where I'd gotten the idea that the exception
> wasn't always instantiated. Perhaps that can happen with
> exceptions that are raised but then caught all within C
> code?

Now that I poke around a bit in Python/errors.c, I think I see how
this is possible.

C code calls PyErr_SetObject (or convenience functions which call
it) to signal an exception; this function takes an exception
type/value pair, like the raise comma syntax.  It does not
instantiate an object; that is done by PyErr_NormalizeException,
which inspects an already-raised exception and, if the exception
type is a class of which the exception value is not an instance,
replaces the value with a new instance of the class.

The implementation of raise -- see Python/ceval.c:/^do_raise --
calls PyErr_NormalizeException if appropriate, so an exception
raised by Python code will get normalized immediately, before e.g.
the stack is unrolled.

But when a C function signals an exception by PyErr_SetObject and
returns NULL, its C caller could indeed deal with the exception
without calling PyErr_NormalizeException, and thus without
actually instantiating an exception object.

At first glance I don't see that this is desirable.  Maybe it's
used for performance in certain for loops or something.

-- 
Steven Taschuk                                                 o- @
staschuk at telusplanet.net                                      7O   )
                                                               "  (





More information about the Python-list mailing list