pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.55k stars 2.09k forks source link

Overload Operator [] to Array index #2702

Closed nyckmaia closed 3 years ago

nyckmaia commented 3 years ago

I was reading the include/pybin11/operator.h...Link here

But I do not found the array index operator in the list. So, look this example below:

class myClass
{

private:
    std::vector<int> _myVec;
public:

    int& operator[](const size_t index) // <== HOW TO EXPOSE THIS TO PYTHON USING PyBind11??
    {
        if (index >= _myVec.size()) {
            std::cerr << "[ERROR]: Array index out of bound!" << std::endl;
            exit(1);
        }

        return _myVec[index];
    }
};

Is this possible?

YannickJadoul commented 3 years ago

@nyckmaia, you can just add a method __getitem__ and __setitem__. operator.h mainly provides some syntactic sugar, but doesn't do anything more than define these special "dunder methods" from Python: https://docs.python.org/3/reference/datamodel.html#object.__getitem__

YannickJadoul commented 3 years ago

Note: the docs just mention it's a shorthand: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#operator-overloading