How to make an extension class have a __getitem__ interface?
sjuranic at gmail.com
Tue Mar 8 23:47:33 CET 2005
I'm in the process of writing a few extension types, and there's one
that I'd sort of like to have getitem, setitem, getslice, setslice
I've been looking through the docs and how things are done in
Objects/listobject.c, and it appears tha there are a couple of ways to
do it and I'd like to get some opinions on what's the best way.
As I see it, here are my options (please correct me if I'm wrong):
1) Register my getitem handler as "__getitem__", my setitem handler as
"__setitem__", etc with my PyMethodDef struct for my new type.
2) Give my new type a full-blown sequence interface and stick my
handlers in the PySequenceMethods struct.
3) Give my new type a full-blown mapping interface and stick my
handlers in the PyMappingMethods struct.
I kind of want to shy away from (2) and (3) simply because there's
still a lot of stuff going on inside those Py(Sequence|Mapping)Methods
structs that I don't understand and I don't want to be responsible for
learning right now. But I'm also not sure if it's just as easy as
setting some functions to respond to __getitem__, __getslice__, etc.
As I'm still new to the world of writing extension modules, any
corrections or clarifications would be greatly appreciated. I've
mostly been using SWIG up to this point, but I've got some code here
where I really care what the Python interface looks like, and SWIG
just won't do what I want it to do (with nested templated classes and
Many thanks in advance.
More information about the Python-list