hpyproject / hpy

HPy: a better API for Python
https://hpyproject.org
MIT License
1.02k stars 52 forks source link

declare exception class? #479

Closed trim21 closed 4 months ago

trim21 commented 4 months ago

it's it possible to create a subclass of Exception and raise it in c code? Did't find api and example for this.

for python code like this:

class MyError(Exception): ...

def func():
    if some_condition:
        raise MyError()
steve-s commented 4 months ago

HPyErr_SetObject? See example in https://github.com/hpyproject/hpy/blob/master/test/test_hpyerr.py#L113.

You can use HPyGlobal to store your exception type in the module exec (e.g., during module initialization). You can create the exception type in C using HPyErr_NewException.

trim21 commented 4 months ago

HPyErr_SetObject? See example in https://github.com/hpyproject/hpy/blob/master/test/test_hpyerr.py#L113.

You can use HPyGlobal to store your exception type in the module exec (e.g., during module initialization). You can create the exception type in C using HPyErr_NewException.

Thanks, it would look like this:

extern HPyGlobal BencodeEncodeError;

static bool init_exception(HPyContext *ctx, HPy mod, HPyGlobal *global, const char *name, const char *attr_name)
{
    HPy h = HPyErr_NewException(ctx, name, HPy_NULL, HPy_NULL);
    if (HPy_IsNull(h))
    {
        return false;
    }
    HPyGlobal_Store(ctx, global, h);
    int set_attr_failed = HPy_SetAttr_s(ctx, mod, attr_name, h);
    HPy_Close(ctx, h);
    return !set_attr_failed;
}

bool init_exceptions(HPyContext *ctx, HPy mod)
{
    init_exception(ctx, mod, &BencodeDecodeError, "_bencode.BencodeDecodeError", "BencodeDecodeError");
    return init_exception(ctx, mod, &BencodeEncodeError, "_bencode.BencodeEncodeError", "BencodeEncodeError");
    // return true;
}

and used like this:

static inline void bencodeError(HPyContext *ctx, const char *data)
{
    HPyErr_SetString(ctx, HPyGlobal_Load(ctx, BencodeEncodeError), data);
}