Johan Råde
Johan Råde

Reputation: 21418

__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.)

Upvotes: 4

Views: 1059

Answers (1)

yak
yak

Reputation: 9041

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.

Upvotes: 6

Related Questions