Search code examples
cython

Can't access class @property from other @property in Cython


I'm learning Cython and ran into the following weird bug


import cython

cdef double MILES_PER_KILOMETER = 0.621371

cdef class Distance:
    cdef double distance, miles, meters, km

    def __cinit__(self, double distance) -> None:
        self.distance = distance

    @property
    def miles(self):
        print(self.km)
        return self.km * MILES_PER_KILOMETER

    @property
    def meters(self):
        print(self.km)
        return self.km * 1000.0

    @property
    def km(self):
        return self.distance

Running this I get

In [2]: from distance_compiled import Distance

In [3]: Distance(42)
Out[3]: <distance_compiled.Distance at 0x7f7a132bc5a0>

In [4]: Distance(42).meters
0.0
Out[4]: 0.0

In [5]: Distance(42).km
Out[5]: 42.0

In [6]: Distance(42).miles
0.0
Out[6]: 0.0

Why is self.km set to 0 when I try to read it from miles and meters?


Solution

  • cdef double distance, miles, meters, km
    

    You have two definitions of miles, meters and km - the properties and the cdef variables with the same name.

    Cython looks to be reading from the cdef variables, which will be automatically zero initialized.