7

I have a Boost Python object

py::object obj = whatever();

I want to print it using normal python rules.

// I want the effect of print 'My object is ', obj
std::cout << "My object is " << obj << std::endl;

This does not compile with a huge compiler dump. How do I do this?

2
  • I'm not that familiar with Boost.Python, but I am not sure it has an operator<<(ostream &) defined for py::object. Commented Dec 16, 2014 at 19:44
  • 2
    You'd probably just want to write the equivalent code to call Python's str() function passing obj as the argument, and convert the return value to an std::string, and stream that out. You could provide your own operator<<(ostream &, py::object const &) to provide the streaming operator for all Python objects using this approach. Commented Dec 16, 2014 at 19:45

1 Answer 1

11

Boost.Python doesn't come with an operator<<(ostream&, const object&) but we can write our own to mimic what Python would do natively: call str:

namespace py = boost::python;

std::ostream& operator<<(std::ostream& os, const py::object& o)
{
    return os << py::extract<std::string>(py::str(o))();
}
Sign up to request clarification or add additional context in comments.

Comments

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.