Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python class inherited from boost-python class copyable

I have a class that inherits from a boost-python class:

class Magnet(CMagnet):   # CMagnet is a C++ based boost-python class
    def __init__(self):
        CMagnet.__init__(self)

    def python_method(self):
        ...

In the C++ implementation of CMagnet I used the code from 1, as posted in 2.

I now have the following problem: When I do the following:

magnet = Magnet()
magnet_2 = copy.deepcopy(magnet)

then magnet is of type Magnet, magnet_2, however, is of type CMagnet. I need it to be also of type Magnet. It lacks all Magnet methods. How do I get deepcopy to copy (and return) the entire Magnet object and not only a copy of the CMagnet part?

like image 482
zeus300 Avatar asked May 24 '19 11:05

zeus300


1 Answers

Since you didn't provide a Minimal, Reproducible Example I cannot quickly check if the following dirty trick works, but I think that it should.

You can add a __deepcopy__() method to your class that delegates the work to the underlying boost-python object and then fixes the type of the result.

def __deepcopy__(self, memo):
    result = super().__deepcopy__(memo)
    result.__class__ = self.__class__
    return result

How do I get deepcopy to copy (and return) the entire Magnet object and not only a copy of the CMagnet part?

Note that the generic__deepcopy__() function copies all fields of the input object, therefore it is only the type that is wrong - the content of the copy object should be correct.

like image 127
Leon Avatar answered Oct 14 '22 23:10

Leon