[BUG]: Failed C++ Assert is Ignored in Python
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
Required prerequisites
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- Consider asking first in the Gitter chat room or in a Discussion.
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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