Search code examples
pythonpython-c-api

__getitem__ method with tuple argument using Python C-API


Is it possible to define a class with a __getitem__ that takes a tuple argument using the Python C-API? The sq_item member of the tp_as_sequence member of a PyTypeObject must be a ssizeargfunc, so I don't see how to do it. (But I assume that the NumPy ndarray does it.)


Solution

  • Yes, use tp_as_mapping instead.

    Its mp_subscript takes a PyObject * so you can use anything as index/key.

    To understand how they relate, you could have a look at the source of PyObject_GetItem() which (as the doc says) is the equivalent of Python o[key] expression. You will see that it first tries tp_as_mapping and if that's not there and key is int, it tries tp_as_sequence.