caketop / python-starlark-go

🐍 Python bindings for starlark-go 🐍
https://python-starlark-go.readthedocs.io/
Apache License 2.0
24 stars 8 forks source link

Support defining functions in Python #230

Closed brandonchinn178 closed 3 months ago

brandonchinn178 commented 5 months ago

In the starlark-go API, you can define arbitrary functions that can return a starlark Value or an error. I wonder if you could do something like

// starlark.c
int cgoPyDict_Check(PyObject *obj)
{
  return PyFunction_Check(obj);
}
// python_to_starlark.go
func pythonToStarlarkBuiltin(obj *C.PyObject) (starlark.Builtin, error) {
    return starlark.NewBuiltin(obj.Name, func(...) (starlark.Value, error) {
        res = obj.Call()
        return res.Value, res.GetException()
    })
}

// python_to_starlark.go::innerPythonToStarlarkValue
switch {
...
case C.cgoPyFunc_Check(obj) == 1:
    value, err = pythonToStarlarkBuiltin(obj)
}