python / python/cpython

Exception that calls `super().__init__` breaks `copy.copy`

未關閉
#125,782 7 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

3.12 3.13 3.14 stdlib type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

For some reason calling Exception.__init__ breaks copy.copys ability to detect args. The following code

import copy

class MyException(Exception):
    def __init__(self, x):
        super().__init__()
        self.x = x

my_exc = MyException(5)
copy.copy(my_exc)

gives

Traceback (most recent call last):
  File "./foo.py", line 9, in <module>
    copy.copy(my_exc)
  File "/usr/lib/python3.12/copy.py", line 97, in copy
    return _reconstruct(x, None, *rv)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/copy.py", line 253, in _reconstruct
    y = func(*args)
        ^^^^^^^^^^^
TypeError: MyException.__init__() missing 1 required positional argument: 'x'

Removing the super().__init__() line makes everything work as expected, but given that it's generally seen as good practice to call super().__init__() in child classes, and you may be working with a more complex class structure, this seems like pretty bad behavior.
I haven't dug deep enough into copy.copy or BaseException.__init__ to decide which one deserves the blame.

For the reason why I want to copy exceptions, see https://github.com/python-trio/flake8-async/issues/298

CPython versions tested on:

3.9, 3.10, 3.11, 3.12, 3.13, 3.14

Operating systems tested on:

Linux

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

使用 copy.copy 重現該範例,並結合 BaseException.init 檢查 /usr/lib/python3.12/copy.py 中的行為。確定初始化器呼叫 super().init() 的 Exception 的預期複製行為,然後新增一個回歸測試,表明複製能夠保留所需的建構函式狀態且不會引發 TypeError。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。