8

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?

1
  • There's a related question which indicates that you should implement the __deepcopy__ yourself, but I don't know if you're already doing it, or if your implementation have any bug; like @Leon said, it's better if you provide a reproducible example. Commented Jun 4, 2019 at 16:16

1 Answer 1

4
+50

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, it works. You are right, it was only the type that was wrong, the methods have been there all the time. The second line in the example you provide should read result = super().__deepcopy__(memo) Providing all the material to recreate the problem, even a minimal set, is not easy with boost python, as it requires quite some of infrastructure to set the whole thing up. But luckily the information provided was sufficient after all.
@zeus300 Fixed the second line. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.