The boost::python::object
's operator[]
returns a boost::python::proxy
object. While the proxy
class has an implicit conversion to boost::python::object
, there are many areas in the API where an explicit conversion is required.
Explicitly constructing a boost::python::object
from the proxy
should resolve the conversion exception:
print(boost::python::object(listObjString[0]));
Here is a complete embedded Python example demonstrating how to print a single element from a list via:
- The Python builtin
print
function - The
PyObject_Print()
function in the Python/C API - Extracting the string representation of an object via
__str__
and printing withstd::cout
#include <boost/foreach.hpp>
#include <boost/python.hpp>
#include <boost/range/irange.hpp>
/// @brief Default flag to have PyObject_Print use the object's
/// __str__ method. The python.h files only define the flag for
/// __repr__.
#define Py_PRINT_STR 0
int main()
{
Py_Initialize();
namespace python = boost::python;
try
{
// Create and populate a Python list.
// >>> list = [x for x in range(100, 103)]
python::list list;
BOOST_FOREACH(int x, boost::irange(100, 103))
list.append(x);
// The proxy returned from a Boost.Python's operator[] provides a
// user-defined conversion to a Boost.Python object. In most cases,
// explicitly invoking the conversion is required.
// Print list[0] using the built-in function print.
/// >>> getattr(__builtins__, 'print')(list[0])
python::object print =
python::import("__main__").attr("__builtins__").attr("print");
print(python::object(list[0]));
// Print list[1] using the Python/C API.
// >>> import sys; sys.stdout.write(list[1].__str__())
PyObject_Print(python::object(list[1]).ptr(), stdout, Py_PRINT_STR);
std::cout << std::endl;
// Print list[2] using the result of the object's __str__ method, and
// extract a C++ string.
std::cout << python::extract<std::string>(
python::object(list[2]).attr("__str__")())() << std::endl;
}
catch (python::error_already_set&)
{
PyErr_Print();
}
}
Output:
100
101
102