C api and exception handling

lallous lallous at lgwm.org
Wed Nov 4 10:00:33 EST 2009


Thanks for your help Carl as usual.

Will go with the getattr override method which is cleaner as you explained.

Regards,
Elias

"Carl Banks" <pavlovevidence at gmail.com> wrote in message 
news:f02c069c-e536-4c6b-b114-2215aa61129e at k17g2000yqh.googlegroups.com...
> On Nov 2, 7:16 am, "lallous" <lall... at lgwm.org> wrote:
>> Hello,
>>
>> Is there is a way, using the Python C api, to install an exception 
>> handler
>> that:
>> - will be triggered when an exception occurs
>> - analyze the reason of the exception
>> - correct the situation and try again (something like exception handling 
>> on
>> windows where the exception handler can retrieve the registers
>> context->faulting instruction->fix situation if needed->restart execution
>> from the same point)
>
> Python has no concept of "retrying", at either the Python or C API
> level.  You might be able to do something Evil in C to get this effect
> but I don't recommend it, it'll be fundamentally averse to how Python
> works and future versions are likely to break it.
>
>
>> Since I will be asked: "what are you trying to achieve?", this is what I
>> want:
>>
>> func_call("hello") <- no exceptions, good code: function is defined and
>> called properly
>> SomeUndefinedFunction("x", "y") <- undefined function call will trigger 
>> an
>> exception. I want my python/C exception handler to inspect the reason of 
>> the
>> exception, if it was a call to an undefined function call then redirect 
>> the
>> execution to a certain method, say: 
>> ExecuteByName("SomeUndefinedFunction",
>> "x", "y")
>>
>> I know if I create a small class with getattr hooked, what I want can be
>> achieved.
>
>
> I'd do it that way.  There is ordinarily no way to hook into a plain
> function call like SomeUndefinedFunction() in Python; if you go around
> hacking up the interpreter to do that users will be highly confused
> and surprised.
>
> OTOH, hooking into attributes is pretty well-known.  When a person
> sees attribute notation they know there's an opportunity to do weird
> stuff.  When a strange function is called, they will be like, "oh,
> someone overrode __getattr__".
>
>
>> But can it be done otherwise (without using a class and instead relying 
>> on
>> exception handlers and correcting the exception)?
>
> Just forget about exception handling.  If you REALLY insist on doing
> this, and I highly recommend against it, the best chance you have is
> to try to hook into the importing process and load a module that uses
> a custom dictionary object.
>
>
> Carl Banks 




More information about the Python-list mailing list