python深拷贝报错_Python copy.deepcopy()失败,不会引发警告,异常或错误

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 what objects can be copied, pickled, marshaled and what objects cannot.

While doing that, I stumbled on this puzzle:

new_obj = copy.deepcopy(my_obj)

function_that_uses_my_new_obj(new_obj)

throws:

function_that_uses_my_new_obj(new_obj)

RuntimeError: Internal C++ object (Pyside.QtGui.QWidget) already deleted

Now, since my_obj is a C++ object, that error I can understand. And the reason for that particular problem is the main topic of the other thread.

However, when I try:

function_that_uses_my_new_obj(copy.deepcopy(my_obj))

I don't get anything at all. The program runs normally to this line, stops there for a few seconds and the execution is stopped, the code after that line is not run, no exception/error/warning is thrown and the Python prompt is ready to accept any new command.

EDIT

For some reason, using the copy() method instead of deepcopy() like so:

function_that_uses_my_new_obj(copy.copy(my_obj))

results in the same exception being thrown. So there has to be some point at which deepcopy decides to stop or is being stopped and that triggers the end of the execution. What I don't get is why nothing is raised to inform the user...

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值