[Python-Dev] PyErr_ Fetch | Restore & friends
Nick Coghlan
ncoghlan at gmail.com
Sat Mar 29 21:47:54 CET 2014
On 30 March 2014 03:05, Ethan Furman <ethan at stoneleaf.us> wrote:
>
> This bit of code won't even finish compiling. I am not sure if my
> understanding of references (and how these functions create/consume them) or
> my understanding of when and where to call PyErr_Fetch|Restore or
> PyException_SetContext is at fault, but I would greatly appreciate somebody
> correcting my understanding. :)
I had to figure this out for the codec exception chaining in Python
3.4, and the main piece that appears to be missing from your code is
an appropriate call to PyErr_NormalizeException(). (The interpreter
tries to avoid actually instantiating exceptions if it can, with the
consequence that explicit normalisation is often needed before
non-trivial operations on the current exception)
This is the code that does the heavy lifting for the codec exception
chaining in Python 3.4:
http://hg.python.org/cpython/file/36492f927a40/Objects/exceptions.c#l2644
Sine you're raising a genuinely new exception, rather than implicitly
replacing an existing one, you don't need all the checks I have in
that function to make sure the implicit replacement is OK. You'd just
need some more like the final section that actually creates the new
exception and links it up with the old one:
http://hg.python.org/cpython/file/36492f927a40/Objects/exceptions.c#l2764
Setting the context correctly for exceptions raised in C should be
similar to that, just setting the context rather than the cause.
(Although don't forget the bit earlier in the function that populates
the traceback correctly on the original exception)
I thought I had filed a "Add a public API to make properly chained
exceptions easier to raise from C" RFE while working on the codec
chaining, but I'm not seeing anything now...
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev
mailing list