[Python] Returning an error instead of raising it from python C API

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    Whether or not it is a good idea (and it probably is considered bad practice), I sometimes return an Error in python instead of raising it.

    def fnA( some_param ):
    # use some_param in complicated thing
    if some_param is None:
    return ValueError( "something went wrong" )

    def fnB( param_a ):
    val = fnA( param_a )
    if isinstance( val, Exception ):
    # error path


    I have been trying to create a python C extension from a regular module that I have written both as practice and because I think it could benefit from it. To do that, I have been using pybind11. It covers most of my needs, except that. I cannot seem to create a ValueError and return it from C (or C++ in this case).

    I have looked at the documentation, at python's own source code and I have not found a way to create an exception without raising it. What I have "found"/tried is this:

    auto some_fn() -> PyExc_ValueError* {
    PyObject* type;
    PyObject* value;
    PyObject* traceback;

    PyErr_SetString( PyExc_ValueError, "error in my function !!!" );
    PyErr_Fetch( &type, &value, &traceback );
    PyErr_NormalizeException( &type, &value, &traceback );
    if( traceback != NULL ) {
    PyException_SetTraceback( value, traceback );
    }
    PyErr_Clear();
    return value;
    }


    which sets the exception, fetches it, normalizes it, clears it and returns the concrete error. I thought it would work but it does not even compile.

    Anyone can point me in the right direction for creating and returning an exception in the C API? It might not really be possible, but then again, it is so easy in python code, I have a hard time believing it can't be done.

    Thanks in any case.

    Continue reading...

Compartilhe esta Página