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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With