Note that adding a __dict__ also massively slows down any cpdef function calls.
On Sat, May 18, 2013 at 10:16 AM, Nils Bruin <nbr...@sfu.ca> wrote: > I don't dare posting this on cython-users because it's a horrible > hack, but it does make a cython class have a dictionary that gets > recognized by python as one to look up attributes in: > > The main problem is to convince Cython to compute the offset of a slot > in a type structure.I ended up importing a C macro for that: > > ######################### > Contents of myheader.h: > #define my_offset(a) (((Py_ssize_t)&(a->__dict__))-((Py_ssize_t)a)) > ######################### > > cdef extern from "myheader.h": > Py_ssize_t my_offset(Test a) > > #make sure we can find tp_dictoffset > cdef extern from *: > ctypedef struct PyTypeExtended "PyTypeObject": > Py_ssize_t tp_dictoffset > > #definition of class with the appropriate attribute > cdef class Test: > cdef public dict __dict__ > def __init__(self): > self.__dict__={} > > #initialization function to force the appropriate tp_dictoffset value > #into the relevant PyTypeObject. This should really be happening > #just before cython calls PyType_Ready, but doing it just afterwards > #doesn't seem to cause problems. > > def equip_Test_with_dict(): > cdef Test t = Test() > (<PyTypeExtended *>(t.__class__)).tp_dictoffset=my_offset(t) > > equip_Test_with_dict() > > > With this loaded, you can do: > > sage: t = Test() > sage: t.a = 1000 > sage: t.a > 1000 > > which would normally not be possible. > > -- > You received this message because you are subscribed to the Google Groups > "sage-devel" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sage-devel+unsubscr...@googlegroups.com. > To post to this group, send email to sage-devel@googlegroups.com. > Visit this group at http://groups.google.com/group/sage-devel?hl=en. > For more options, visit https://groups.google.com/groups/opt_out. > > -- You received this message because you are subscribed to the Google Groups "sage-devel" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-devel+unsubscr...@googlegroups.com. To post to this group, send email to sage-devel@googlegroups.com. Visit this group at http://groups.google.com/group/sage-devel?hl=en. For more options, visit https://groups.google.com/groups/opt_out.