Exceptions from callbacks

Jonathan Giddy jon at rdt.monash.edu.au
Thu Nov 4 03:52:50 CET 1999

Eric Dorland <dorland at lords.com> writes:

>I understand what you mean exactly. The problem is I can't do it that
>way. Basically, the way the library works is that you register a bunch
>of callbacks and then call a function (eg. Loop()) that doesn't return.
>The HandlePendingEvents (its equivalent I mean :)) isn't exposed by the
>library, so I can't wrap it :). That's way I want a way to force the
>interpreter to realize an exception is there. Is there a way, or a work
>around, to do this?

Are you saying that there is no way to tell the function "Loop" to return?
Forgetting Python for a moment, can you even write a C program that breaks 
out of the loop to handle errors?

If so, then you can change Randall's example callback to the code below.

If not, then you have the problem that the Python interpreter *is* a C 
program.  If a C program can't do it, then neither can Python.

  static void _wrap_MYLIBCallback( void )
    /*  C callback used to relay to Python callable objects.  */

    /*  Pass the buck onto Python  */
    pyresult = PyEval_CallObject( pyfunc, pyargs );     /*  Call Python     */
    Py_DECREF( pyargs );                                /*  Trash arg list  */
    if ( pyresult )
      Py_DECREF( pyresult );                            /*  Trash any result*/
      /* An exception occurred, do whatever tells the loop to exit */

    /*  If the callback threw an exception, it will be propagated across    */
    /*    the C layer ( we check PyErr_Occurred() on the other side).       */

More information about the Python-list mailing list