pybind / pybind/pybind11

[FEAT] str operator like Boost.Python

Open
#2,518 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Assume I have class/struct Foo and operator std::ostream& operator<<(std::ostream&, const Foo&). In Boost.Python, one can use something like:

.def(str(self))

to enable the use of print(foo) from Python. See discussion here.

Currently, I'm only aware of the following usage to get print(foo) to work using pybind11:

.def("__str__", [](const Foo& self) { std::stringstream ss;  ss << self; return ss.str(); })

I wonder if there is a more convenient way of doing this already in pybind11.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository file or test is named. Start by examining the .def(str(self)) Boost.Python pattern, the str lambda workaround, and pybind11's .def binding entry point; done means a convenient way for print(foo) to use Foo's operator<<, with the behavior covered by a test.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.