FAQ cdef_derive - cython/cython GitHub Wiki
Note that this example further down is outdated as of Cython 0.14. Do not do this! Instead, inherit from the normal Python type, e.g.
# Cython 0.14 and later
cdef class ObjectList(list):
def foo(self):
return list(self)
For Pyrex and older Cython versions, here is an example from Greg Ewing illustrating deriving from a builtin type (using the sage notebook):
%cython
cdef extern from "listobject.h":
ctypedef class __builtin__.list [object PyListObject]:
pass
cdef class ObjectList(list):
def foo(self):
return list(self)
v = ObjectList([1,2,3])
type(v.foo()) /// <type 'list'>
Note that you cannot subtype neither PyStringObject (__builtin__.str) this way, as it will break the way the string is allocated by Python, nor PyTupleObject (__builtin__.tuple).