hpy icon indicating copy to clipboard operation
hpy copied to clipboard

Simpler & more typesafe API for type-specific calls

Open antocuni opened this issue 5 years ago • 15 comments

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:

  1. reduce the number of API functions
  2. make it possible to call functions with or without type checking
  3. 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);
}

antocuni avatar Nov 26 '19 14:11 antocuni