Home > Enterprise >  C Python How to create a function inside another function as a decorator using C
C Python How to create a function inside another function as a decorator using C

Time:02-14

I would like to know how to create a Python function inside another Python function using C? Try something like this:

static PyObject *func(PyObject *self, PyObject *wrap) { // METH_O
       PyObject *newfunc(PyObject *self, PyObject *args, PyObject *kwds) = { return PyObject_Call(wrap, args, kwds); }
       return newfunc;
}

But the compiler expects another expression. I would like to know (or some clues) to advance my project, How to create a function inside another python function using C?

CodePudding user response:

C does not have closures. You cannot create a C function inside another C function and give it access to local variables from the function that defined it. Even if you could, the new C function would not be directly usable as a Python function.

You can write Python classes in the Python C API, and this is the usual way to write Python decorators in C. For example, instead of writing

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

a decorator written in C would look more like the C API equivalent of

class decorator:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

A full, detailed guide on how to create Python classes in C would be beyond the scope of this answer. See the previously linked documentation for a tutorial, and note that the C-level hook for __call__ is the tp_call slot.

You can look at the C implementation of functools.partial for an example, either the old 3.6 implementation for a simple example or a more recent version if you want to get fancy with the new vectorcall mechanism.

  • Related