I have a class which contains a std::vector<Foo> where Foo is a class containing a key, value, comment, etc. Please note that there is a reason why I am using a vector and not a dictionary.
I have overloaded the subscript operator in C++ such that foos["Key Name"] will search through the vector for a Foo object with key matching “Key Name” (where foos is a std::vector<Foo>).
I use SWIG to create a Python wrapper for my library, and I would really like for this subscript operator to extend into Python. In other words, I want to be able to use the foos["Key Name"] for finding objects in the vector in Python.
Any tips on how to make SWIG recognize the subscript operator and overload it in Python? I am a little surprised that I couldn’t find examples of people doing this online. I guess most people just use a std::map and have SWIG convert it to a Python dict.
In straight Python, if you want to overload the subscript operator, you would create a
__getitem__and__setitem__class method. As a simple example:So if you want to have C++ handle this, my very best guess (no, I haven’t verified this) is that you would create a
__getitem__and__setitem__in C++. You can either do this directly in your C++ code, or use the%extenddirective within SWIG to call off to your C++[]operator.