Does this mean once you define a python class with cdef all self.* attributes have to be cdef defined?
Yes. This is stated pretty explicitly in the documentation:
Attributes in cdef classes behave differently from attributes in regular classes:
- All attributes must be pre-declared at compile-time
- …
You can quite happily store a string by defining the attribute to be of type object:
cdef public object msg
Internally, the reason for this is that the cdef class
does not have a dictionary, which saves space and makes attribute access faster, but it does mean that it cannot have arbitrary attributes added at runtime. This is reasonably similar to using __slots__
in a normal Python class.