pybind / pybind/pybind11

[BUG]: Failed C++ Assert is Ignored in Python

Open
#5,106 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Required prerequisites
What version (or hash if on master) of pybind11 are you using?

2.12.0

Problem description

In the C++ overloading of the operator[], I've got an assert to make sure the id being accessed isn't outside the bounds of my container. This works in the C++ code, but in Python, it gives no indication of the assert failure when accessing an invalid id and still returns a value, though I'm not sure where this value is coming from. Below is a reproduction of this behavior.

Reproducible example code
#include <pybind11/pybind11.h>
#include <pybind11/operators.h>

#include <array>
#include <assert>

class foo {
public:
        std::array<int, 4> data{1, 2, 3, 4};
        size_t size = 4;

        double operator[](const size_t idx) {
                assert(idx < this->size);
                return this->data[idx];
        }
};

namespace py = pybind11;

PYBIND11_MODULE(assert_issue, m) {
        py::class_<foo>(m, "foo")
                .def(py::init<>())
                .def("__getitem__", py::overload_cast<const size_t>(&foo::operator[]));
}
Is this a regression? Put the last known working version here if it is.

Not a regression

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

Start with the reproducer's foo::operator[] assertion and the py::class_ getitem binding using py::overload_cast. Run the invalid-id access against pybind11 2.12.0, then trace whether the assertion failure is propagated through the Python call; done means the behavior is explained and covered by an appropriate regression test or clearly identified as external to pybind11.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.