Skip to content

[BUG]: py::object augmented assignment doesn't work with immutable types #3812

Closed
@oremanj

Description

@oremanj

Required prerequisites

Problem description

The augmented assignment operators (operator+=, etc) on py::object are implemented analogously to the regular binary operators (operator+, etc): they call one of the PyNumber_ API functions and return the result. For immutable types such as py::str, PyNumber_InPlaceAdd is implemented the same as PyNumber_Add, so you need to look at the result in order to see any change; in both C++ and Python, though, foo += bar is supposed to be sufficient to update foo on its own without observing the result of the expression.

Reproducible example code

#include <pybind11/pybind11.h>

namespace py = pybind11;
using namespace pybind11::literals;

PYBIND11_MODULE(example, m) {
    m.def("test", []() -> py::str {
        py::str text = "foo"_s;
        text += " bar"_s;
        return text;
    });
}

// import example
// assert example.test() == "foo bar"
//    --> fails: example.test() actually returns "foo"

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions