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?
The C PyObject structure contains the fields tp_as_number , tp_as_sequence and tp_as_mapping . In
Share
Those methods are the equivalent of python’s special methods, and are called in the same circumstances. For example
tp_as_number->nb_addis called when executinga + bandais the extension type.It is the equivalent of
__add__. Theinplace_*functions are the equivalents of__i*__methods.Note that the
__r*__methods are implemented simply swapping arguments to the normal functions, thus5 + awhereais an extension type will first try to call the numeric version ofnb_add, after this failed it triesnb_addofaputting5as first argument andaas the second one.The same is true for the
tp_as_mappingandtp_as_sequencestructs. Themp_lengthandsq_lengthfunctions are called by the built-in functionlen, and are the equivalent of__len__. Theoretically you could implement different functions formp_lengthandsq_length, in which case thesq_lengthhas 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. Thesq_concatis called after tryingnb_add, and thus an extension type can support+operator without having annb_addfunction set.