是否存在无法为其创建深拷贝的对象? [英] Are there objects for which it is impossible to create a deep copy?

查看:33
本文介绍了是否存在无法为其创建深拷贝的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行以下行时收到一条错误消息:

I get an error message when I execute the following line:

img = copy.deepcopy(img_file_obj)

img_file_obj 具有以下类型:

<class 'werkzeug.datastructures.FileStorage'>

是否不允许创建文件存储对象的深拷贝?

Is it not allowed to create a deep copy of a file storage object?

添加

我可能需要解释为什么我要尝试创建文件存储对象的副本.在我的代码最后执行:

I probably need to explain why I am trying to create a copy of a file-storage object. In the end of my code I execute:

img_obj.save(fname)

但在此之前我会检查文件有多大.我是通过以下方式做到的:

But before that I check how big the file is. I do it in the following way:

img_obj.seek(0, os.SEEK_END)
size = img.tell()

问题是检查大小会破坏"文件.如果我检查文件大小然后保存它,我会在磁盘上得到一个空文件.这就是为什么我想创建文件对象的副本,检查副本的大小,如果大小可以接受,则将原始文件对象保存在磁盘上.

The problem is that the checking of the size "destroys" the file. If I check the file size and then save it, I get an empty file on the disk. It is why I wanted to create a copy of the file-object, check the size of the copy and, if the size is acceptable, save the original file-object on the disk.

推荐答案

是否存在无法为其创建深拷贝的对象?

Are there objects for which it is impossible to create a deep copy?

是的.

任何类型覆盖标准 __deepcopy__ 的对象(或注册了 copyreg) 引发异常的函数不能被深度复制.

Any object whose type overrides the standard __deepcopy__ with (or registers with copyreg) a function that raises an exception can't be deep-copied.

任何类型使用标准__deepcopy__但不能被(浅)复制的对象不能被深复制.

Any object whose type uses the standard __deepcopy__ but can't be (shallow-)copied cannot be deep-copied.

任何带有不能被深度复制的子元素(无论是由标准__deepcopy__ 还是它自己的实现选择)的对象都不能被深度复制.

Any object with sub-elements (whether selected by the standard __deepcopy__ or its own implementation) that cannot be deep-copied cannot be deep-copied.

而且有很多种对象甚至不能浅拷贝.copy 模块的文档提供了一些示例:

And there are many kinds of objects that can't be even shallow-copied. The documentation for the copy module gives some examples:

此模块不会复制模块、方法、堆栈跟踪、堆栈帧、文件、套接字、窗口、数组或任何类似类型等类型.

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types.

并不是说不可能复制文件,而是它的含义非常模糊(它应该复制文件句柄、重新打开文件还是共享句柄?它应该以相同的文件指针?它的缓冲区或有状态编码器是否必须处于相同状态?),因此使它们可复制更容易误导.

Not that it would be impossible to copy a file, but what it would mean is pretty ambiguous (should it dup the file handle, reopen the file, or share the handle? should it start with the same file pointer? does its buffer or stateful encoder have to be in the same state?), so it would be more misleading than helpful to make them copyable.

当然,Werkzeug 框架可以选择使其 FileStorage 对象可复制,即使标准 Python 文件对象不可复制,但他们可能有相同的理由不这样做.

Of course the Werkzeug framework could have chosen to make its FileStorage objects copyable even though standard Python file objects aren't, but they presumably had the same reasons not to.

这篇关于是否存在无法为其创建深拷贝的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆