1

I have a vector class I have defined in cython, and I am trying to show some of the attributes to users. I want to iterate over them using the __dict__ attribute, but I'm getting an error that my object does not contain that attribute. Is it possible to use the __dict__ attribute on instances of cython defined objects?

For example:

from my_cython_lib import vector

v1 = Vector()
for attrtibute in v1.__dict__:
    # do stuff to the attribute

My vector class:

cdef class Vector:
    def __cinit__(self):
        self.x = None
        self.y = None
        self.z = None
  • 2
    The whole point of something like a Cythonized class is that you aren't creating a bloated python object that carries around a 200+ byte dict just as a namespace. – juanpa.arrivillaga Jan 15 '20 at 20:30
  • Perhaps you could iterate over `dir(vector)` and get the attribute with `getattr(vector, attr)`. – N Chauhan Jan 15 '20 at 20:34
  • Fair point, juanpa, and yes perhaps iterating over in a different way would be more wise. – Saucy Dumpling Jan 15 '20 at 20:35
  • It's possible to force Cython to use a dict for the attributes, but doing so negates most of the point of using Cython. – user2357112 Jan 15 '20 at 20:38
  • Funny, some time ago your `cdef class Vector` would not compile, see https://stackoverflow.com/q/42632297/5769463. That might be a bug, as the documentation isn't updated: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#dynamic-attributes – ead Jan 15 '20 at 21:02
  • Huh interesting. I have had no problems mixing cdef, cpdef, and def in cython classes. – Saucy Dumpling Jan 15 '20 at 21:10
  • @ead The code as presented compiles but throws an exception in the constructor (as I'd expect). Of course, that isn't really the point of the question... – DavidW Jan 15 '20 at 21:24
  • @DavidW you are right, I have only remembered, that it didn't work, but overlooked the "during the run time" part. – ead Jan 15 '20 at 21:28

0 Answers0