PyEval_EvalCodeEx return value

John Pinner funthyme at
Tue Sep 20 10:40:06 EDT 2011

On Sep 20, 11:34 am, Mateusz Loskot <mate... at> wrote:
> Hi,
> I'm trying to dig out details about what exactly is the return
> value the of PyEval_EvalCodeEx function in Python 3.x
> The documentation is sparse, unfortunately.
> Perhaps I'm looking at wrong function.
> My aim is simple, I need to execute Python code using Python interpreter
> embedded in my C++ application.
> The Python code is a simple script that always returns single value.
> For example:
> #! /usr/bin/env python
> def foo(a, b):
>     return a + b
> f = foo(2, 3)
> But, f can be of different type for different script: one returns
> numeric value, another returns a sequence, so the type is not
> possible to be determined in advance.
> I know how to capture Python stdout/stderr.
> I also know how to access the "f" attribute using
> PyObject_GetAttrString and then I can convert "f" value to C++ type
> depending on PyObject type.
> However, I guess there shall be a way to access "f" value
> directly from PyEval_EvalCode return object:
> PyObject* evalRet = ::PyEval_EvalCode(...);
> But, I can't find any details what the "evalRet" actually is.

I assume that you have read the documentation at,
and I agree that it's sparse, but the entry for the next entry,
PyEval_EvalCodeEx, tells you a little more, as does that for

Obviously, it's returning a pointer to a PyObject, and Looking at the
source code, that may be NULL, to throw an exception, or an execution
frame, or a generator,etc, etc, depending on the code it's been given.
I guess that you should be able to inspect the PyObject to see what it

What I'm wondering is, why are you eval-ing code ? A favourite device
of C programmers coming to Python (and mea culpa in the past), it's
fraught with potential problems and even security risks, and is
difficult to debug, and maybe you should be using introspection

And maybe you should be working in Python, and not C++ at this point,
do the dynamic stuff in the language best suited, and then return to C+
+ when needed.

Best wishes,


> Any pointers would be helpful.
> Best regards,
> --
> Mateusz Loskot,
> Charter Member of OSGeo,
> Member of ACCU,

More information about the Python-list mailing list