This section aims to give a quick fly-by on the various type methods you can implement and what they do.
Here is the definition of PyTypeObject, with some fields only used in debug builds omitted:
typedef struct _typeobject { PyObject_VAR_HEAD char *tp_name; /* For printing */ int tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; printfunc tp_print; getattrfunc tp_getattr; setattrfunc tp_setattr; cmpfunc tp_compare; reprfunc tp_repr; /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; /* More standard operations (here for binary compatibility) */ hashfunc tp_hash; ternaryfunc tp_call; reprfunc tp_str; getattrofunc tp_getattro; setattrofunc tp_setattro; /* Functions to access object as input/output buffer */ PyBufferProcs *tp_as_buffer; /* Flags to define presence of optional/expanded features */ long tp_flags; char *tp_doc; /* Documentation string */ /* call function for all accessible objects */ traverseproc tp_traverse; /* delete references to contained objects */ inquiry tp_clear; /* rich comparisons */ richcmpfunc tp_richcompare; /* weak reference enabler */ long tp_weaklistoffset; } PyTypeObject;
Now that's a lot of methods. Don't worry too much though - if you have a type you want to define, the chances are very good that you will only implement a handful of these.
As you probably expect by now, I'm going to go over this line-by-line, saying a word about each field as we get to it.
char *tp_name; /* For printing */
The name of the type - as mentioned in the last section, this will appear in various places, almost entirely for diagnostic purposes. Try to choose something that will be helpful in such a situation!
int tp_basicsize, tp_itemsize; /* For allocation */
These fields tell the runtime how much memory to allocate when new objects of this typed are created. Python has some builtin support for variable length structures (think: strings, lists) which is where the tp_itemsize field comes in. This will be dealt with later.
Now we come to the basic type methods - the ones most extension types will implement.
destructor tp_dealloc; printfunc tp_print; getattrfunc tp_getattr; setattrfunc tp_setattr; cmpfunc tp_compare; reprfunc tp_repr;
See About this document... for information on suggesting changes.