3

I'm trying to port an extension module from 2.7 to 3.5. The extension module uses PyEval_EvalCode. It does this with some code similar to the following:

struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
if (compiled_node)
{
    PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
    if (compiled_code)
    {
      return_value.Reset(PyEval_EvalCode (compiled_code, globals.get(), locals.get()));
    }
}

In Python 2.7 this works fine. In Python 3.5 I get a compilation failure, because PyNode_Compile returns a PyCodeObject, but in Python 3.5 PyEval_EvalCode accepts a PyObject*. What do I need to do to convert this into a PyObject that I can pass to PyEval_EvalCode?

0

1 Answer 1

4

For the vast majority of Python types, PyObject is the "parent" struct of the type. Try casting the argument: (PyObject*)compiled_code.

The Code Objects docs make it clear that PyObject* can be PyCodeObject* (otherwise PyCode_Check wouldn't exist), so if you know it's a code object, the cast is safe.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's weird that they decided to have PyNode_Compile return a PyCodeObject instead of a PyObject like all the other methods do. That threw me for a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.