Domanda

I have a simple Cython class where I define what it means to compare two objects for equality (==):

cdef class MyClass:
  cdef public int a
  cdef public int b
  def __init__(self, a, b):
    self.a = a
    self.b = b

  def __richcmp__(self, MyClass other, int op):
    if op == 2:
      if (self.a == other.a) and (self.b == other.b):
        return True
      return False
    raise Exception, "No other op"

If I make an instance of MyClass in Python and then copy it, it breaks the object:

import copy
myobj = MyClass(5, 10)
myobj_copy = copy.copy(myobj)
# myobj_copy is now defective
# ..

what is the correct way to create copies of instances of Cython classes? I want to make a copy and then modify it without affecting the original object. update to be clear, MyClass also inherits from another Cython (cdef) class.

È stato utile?

Soluzione

You should define a __copy__ method for your class. Adding eg.

def __copy__(self):
    return MyClass(self.a, self.b)

to your code gives:

>>> import cp
>>> foo = cp.MyClass(5, 10)
>>> import copy
>>> bar = copy.copy(foo)
>>> bar == foo
True

As an alternative, if you want also to pickle your object you may want to implement The pickle protocol for extension type that is a __reduce__ method. Then it will be used for copying.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top