Skip to content Skip to sidebar Skip to footer

Python Copy.deepcopy() Fails Without Raising Warning, Exception Or Error

This question is related to another question I posted yesterday, although it is much more general in nature. Because of the thread I mentionned, I have been trying to determine wha

Solution 1:

Copy and pickle will try to do their job in all cases, but as for many things in python, the responsibility of the result is placed on the programmer only.

In order of rising difficulty:

  1. The objects that really can be safely copied or pickled are basically the primitive types, strings, lists, dictionaries, numbers, etc.

  2. Then there are many objects that explicitly support the magic methods (like __copy__ and __deepcopy__)

  3. Then there are the objects on which copy will do its best and succeed. For simple objects, that contain only references to objects in the previous levels.

  4. Finally the really unsafe to copy:

    • Large object graphs with many circular references
    • Object that are being used and modified by other threads.
    • Object with external resources: files, connections, etc.
    • Object that wrap or proxy C libraries

Solution 2:

Your assertion that "my_obj is a C++ object" looks pretty obviously false: my_obj is actually a python wrapper around a C++ object. So code such as:

widget = QtGui.QWidget()
    my_obj = copy.deepcopy(widget)

will only create a copy of the python wrapper, leaving the underlying C++ object untouched. This explains why attempting to call one of the copied wrapped methods will produce that RuntimeError. The copy of the wrapper never had a corresponding underlying C++ object, and so it behaves as if it has been deleted.

This kind of thing can happen quite easily in "normal" PySide/PyQt code. Sometimes, if you don't take care to keep a reference to an object on the python side, Qt can delete the C++ part, leaving you with an "empty" wrapper. And in such situations, you will see the exact same RuntimeError.

Post a Comment for "Python Copy.deepcopy() Fails Without Raising Warning, Exception Or Error"