using special function such as __add__ in cython cdef classes
20:27 01 May 2022

I am wanting to create a cython object that can has convenient operations such as addition multiplication and comparisons. But when I compile such classes they all seem to have a lot of python overhead.

A simple example:

%%cython -a

cdef class Pair:
    cdef public:
        int a
        int b
        
    def __init__(self, int a, int b):
        self.a = a
        self.b = b
        
    def __add__(self, Pair other):
        return Pair(self.a + other.a, self.b + other.b)

p1 = Pair(1, 2)
p2 = Pair(3, 4)

p3 = p1+p2

print(p3.a, p3.b)

But I end up getting quite large readouts from the annotated compiler It seems like the __add__ function is converting objects from python floats to cython doubles and doing a bunch of type checking. Am I doing something wrong?

cython