Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 623
Johan Råde Avatar asked Oct 19 '25 06:10

Johan Råde


1 Answers

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.

like image 89
yak Avatar answered Oct 21 '25 20:10

yak