Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How to create lambda PyObject from its Python code in a C string?

$
0
0

I have the following code in Python, which uses pyjexl module:

import pyjexljexl = pyjexl.JEXL()jexl.add_transform("lowercase", lambda x: str(x).lower())

I want to do the same using Python C API. Something like this:

Py_Initialize();PyObject* pyjexlModule = PyImport_ImportModule("pyjexl");PyObject* jexl = PyObject_CallMethod(pyjexlModule, "JEXL", NULL);const char* myLambda = "lambda x: str(x).lower()";PyObject* lambda = ... /* something using myLambda */PyObject_CallMethod(jexl, "add_transform", "sO", "lowercase", lambda);

(Simplified version of the code, e.g., NULL checking and Py_XDECREF() have been omitted)

The problem I'm trying to solve is how to get a PyObject representing a lambda function which Python code is contained in the C-string myLambda.

How can I achieve this?

I have tried with the suggestion by @DavidW using this:

PyObject* globals = PyDict_New();PyObject* locals = PyDict_New();PyObject* lambda = PyRun_String(myLambda, Py_eval_input, globals, locals);

But I think it's not working, as the resulting lambda variable (inspected using debugger) is of type PyNone:

Debugger screenshot


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>