hpy
hpy copied to clipboard
Simpler & more typesafe API for type-specific calls
The current C-API provides lots of functions which are duplicate, the only difference being whether they do a typecheck of the argument or not.
E.g., PyTuple_GET_SIZE
vs PyTuple_Size
, PyTuple_GET_ITEM
vs PyTuple_GetItem
, etc.
The following idea tries to:
- reduce the number of API functions
- make it possible to call functions with or without type checking
- use the C typesystem to catch some errors at compile time
The idea is to have special C types of handles which represent specialized objects and/or protocolos, e.g. HPyTuple
. You can cast an HPy
to HPyTuple
with or without typechecks. Functions like HPyTuple_Size
takes and HPyTuple
argument, so it is impossible to call them with an HPy
. For example:
typedef struct { long _i; } HPy;
typedef struct { long _i; } HPyTuple;
#define HPyTuple_CAST(x) ((HPyTuple){x._i})
void print_tuple(HPyContext ctx, HPy obj)
{
// no typecheck, we assume that the user knows that obj is a tuple
//HPyTuple t = HPyTuple_CAST(ctx, obj);
// typecheck. "obj" is automatically closed
HPyTuple t = HPyTuple_Check(ctx, obj); // or maybe HPyTuple_TryCast?
if (HPy_IsNull(t))
return HPy_NULL;
// the HPyTuple_* functions DO NOT do any form of typechecking
long n = HPyTuple_Size(ctx, t);
for (int i=o; i < n; i++) {
HPy item = HPyTuple_GetItem(ctx, t, i)
HPy_Print(ctx, item);
HPy_Close(cts, item);
}
HPy_Close(ctx, t);
}