hpyproject / hpy

HPy: a better API for Python

Home Page:https://hpyproject.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

declare exception class?

trim21 opened this issue · comments

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()

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.

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);
}