The C PyObject structure contains the fields tp_as_number
, tp_as_sequence
and tp_as_mapping
. In which circumstances are these invoked? Can anybody provide some example Python code which would result in these C methods being called?
1 Answers
Those methods are the equivalent of python's special methods, and are called in the same circumstances. For example tp_as_number->nb_add
is called when executing a + b
and a
is the extension type.
It is the equivalent of __add__
. The inplace_*
functions are the equivalents of __i*__
methods.
Note that the __r*__
methods are implemented simply swapping arguments to the normal functions, thus 5 + a
where a
is an extension type will first try to call the numeric version of nb_add
, after this failed it tries nb_add
of a
putting 5
as first argument and a
as the second one.
The same is true for the tp_as_mapping
and tp_as_sequence
structs. The mp_length
and sq_length
functions are called by the built-in function len
, and are the equivalent of __len__
. Theoretically you could implement different functions for mp_length
and sq_length
, in which case the sq_length
has precedence(this can be seen from the source code, even though I don't know whether this behaviour is documented).
Also note that, for example, the +
operator can be implemented in different functions. The sq_concat
is called after trying nb_add
, and thus an extension type can support +
operator without having an nb_add
function set.

- 98,325
- 22
- 197
- 231
-
Many thanks. Would appreciate if you could point me to some further doc, if there is any... – isedev Feb 09 '13 at 13:10
-
1@isedev You can find some documentation [here](http://docs.python.org/2/c-api/objimpl.html). You can also find some information in the [tutorial](http://docs.python.org/2/extending/newtypes.html#abstract-protocol-support) – Bakuriu Feb 09 '13 at 13:17