pybind / pybind/pybind11

[QUESTION] How can I overload the [ ] operator?

Open
#3,072 11 comments 0 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

I understand how the other operators are overloaded but I'm having difficulty with this one.
This is my code (simplified):

float& Vec::operator[](unsigned i)
{
    return privatedata[i];
}

py::class_<Vec>(m, "Vec")
      .def(py::init<unsigned &>())
      .def(unsigned() [] float());

It may not come as a surprise that this does not work. Since a Vec object is not passed in or out of the operator directly, my binding cannot contain py::self. Please let me know what I'm doing wrong! Thanks everyone.

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

The issue names no repository files, tests, or entry points. Start by determining whether a documentation example or another repository change is wanted; done should be a maintainer-approved explanation of how this operator binding should be handled.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.