piątek, 8 kwietnia 2011

Python: C extensions - sequence-like object

If class have to support standard len() function or operator in, then must be a sequence-like. This require variable of type PySequenceMethods, that store addresses of proper functions. Finally address of this structure have to be assigned to tp_as_sequence member of main PyTypeObject variable.

Here is sample code:

static PySequenceMethods class_seq;

static PyTypeObject class_type_dsc = {
 ...
};

ssize_t
classmeth_len(PyObject* self) {
 if (not error)
  return sequence_size;
 else
  return -1;
}

int
classmeth_contains(PyObject* self, PyObject* value) {
 if (not error) {
  if (value in self)
   return 1;
  else
   return 0;
 }
 else
  return -1;
}


PyMODINIT_FUNC
PyInit_module() {
 class_seq.sq_length   = classmeth_len;
 class_seq.sq_contains = classmeth_contains;

 class_type_dsc.tp_as_sequence = &class_seq;

 ...
}

Brak komentarzy: