`copy.copy` ignores methods of the object which are not part of the class
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
from types import MethodType
from copy import copy, deepcopy
class MyClass:
def __copy__(self):
print("Call __copy__ of class")
return self
def __deepcopy__(self, memo):
print("Call __deepcopy__ of class")
return self
obj1 = MyClass()
obj2 = MyClass()
def copy_func(self):
print("New copy function")
return self
def deepcopy_func(self, memo):
print("New deepcopy function")
return self
obj11 = copy(obj1)
# > Call __copy__ of class
obj12 = deepcopy(obj1)
# > Call __deepcopy__ of class
obj21 = copy(obj2)
# > Call __copy__ of class
obj22 = deepcopy(obj2)
# > Call __deepcopy__ of class
obj1.__copy__ = copy_func.__get__(obj1)
obj1.__deepcopy__ = deepcopy_func.__get__(obj1)
obj2.__copy__ = MethodType(copy_func, obj2)
obj2.__deepcopy__ = MethodType(deepcopy_func, obj2)
obj13 = copy(obj1)
# > Call __copy__ of class
obj14 = deepcopy(obj1)
# > New deepcopy function
obj23 = copy(obj2)
# > Call __copy__ of class
obj24 = deepcopy(obj2)
# > New deepcopy function
Knowing, that binding additional methods to an object after instantiation might not be recommended, the behavior shown above confuses me. My expectation is that copy.copy and copy.deepcopy both use the __copy__/__deepcopy__ method of the actual object passed to it (code). However, copy.copy does not, but rather uses the __copy__ method of the class which could be different from that of the object (code).
Historically, the behavior of copy.copy and copy.deepcopy was first identical (c06e3acc735a6e9cf28d0f511493bcfd8829117d, using the method of the class in both cases), but lateron changed (e690883ccf8081e5baab0e9d71f596f26245b569).
Apart from the differences between the behavior of copy.copy and copy.deepcopy w.r.t. the __copy__/__deepcopy__ methods, the copy.copy method itself takes two different approaches when looking for methods to create the copy: __copy__ is searched inside the class, and in case it is not found, the __reduce_ex__/__reduce__ are looked up in the object (code).
CPython versions tested on:
3.11
Operating systems tested on:
Linux
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Lib/copy.py 开始,检查报告中链接的 copy 和 reduction lookup 路径,然后在受支持的 Python 版本上运行提供的 reproducer。查看提到的历史提交,以了解为什么 copy.copy 和 copy.deepcopy 会出现分歧。当实例绑定的 copy 和 deepcopy 方法的行为得到一致解决,并由适当的回归测试覆盖时,即视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100