Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

monkeypatch.setattr fails to undo on objects with a custom __setattr__ (regression from #14969)

未关闭 适合新手
#15,099 6 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@hardikkaurani 已经在做这个了。

开始于 2026年9月24日。

  • #15100 来自 @hardikkaurani —— 未关闭
  • #15104 来自 @Maurenz2530 —— 未关闭
  • #15106 来自 @chen-maker999 —— 已关闭,未合并
  • #15118 来自 @Tejas5405 —— 未关闭
  • #15136 来自 @RonnyPfannschmidt —— 未关闭

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
78/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python
领域
testing-qa

调研方向

从 MonkeyPatch.setattr 中的新分支开始,并将其与 issue 中描述的先前行为进行比较。向 test_proxy.py 添加一个使用自定义 setattr/getattr 对象的回归用例,然后运行该测试,以验证 undo 会恢复原始值,并且修补后的值不会泄漏到后续测试中。

由索引模型根据 Issue 内容生成。

描述

Since #14969 (0c601d510, not released yet), monkeypatch.setattr doesn't restore attributes on objects that store them somewhere other than __dict__ through a custom __setattr__/__getattr__. Undo raises AttributeError, and the patched value leaks into later tests.

class Config:
    """Stores attributes in a private dict instead of __dict__."""
    def __init__(self):
        object.__setattr__(self, "_data", {"debug": False})
    def __getattr__(self, name):
        try:
            return self._data[name]
        except KeyError:
            raise AttributeError(name) from None
    def __setattr__(self, name, value):
        self._data[name] = value

cfg = Config()

def test_patch(monkeypatch):
    monkeypatch.setattr(cfg, "debug", True)
    assert cfg.debug is True

def test_restored():
    assert cfg.debug is False

On main:

ERROR test_proxy.py::test_patch - AttributeError: 'Config' object has no attribute 'debug'
FAILED test_proxy.py::test_restored - assert True is False
1 failed, 1 passed, 1 error

Just before 0c601d510, the same file passes (2 passed).

The new branch in MonkeyPatch.setattr takes the old value from target.__dict__.get(name, NOTSET) whenever target has a __dict__. It assumes that a plain setattr() writes into that dict. With a custom __setattr__ it doesn't, so the old value is recorded as NOTSET. undo() then calls delattr(cfg, "debug") instead of setting it back to False. That delattr fails, and the value stays patched.

@Shriprasad-P pointed out this exact case in a review on #14969, but it wasn't addressed before the merge. I'm opening this issue so it gets fixed before the next release.

One possible direction: only use the __dict__ lookup when name is actually present in the instance __dict__, or when the type uses object.__setattr__. Otherwise fall back to the value from getattr(), as before.

pytest 9.2.0.dev345+g872117358, Python 3.13.5, Windows 11.

主要语言
Python
星标
14.6k
派生
3.5k
平均合并
3 天 15 小时
30 天内合并 PR
28

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

pytest-dev/pytest 的其他 Issue

查看 pytest-dev/pytest 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。