python / python/cpython

Misleading "Not an instance or subtype" error when assigning to property of frozen, slotted dataclass

未关闭
#143,969 6 条评论 2 个 reaction 已指派 1 人 在 GitHub 查看

@sobolevn 已经在做这个了。

开始于 2026年5月19日。

stdlib topic-dataclasses type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

When a dataclass is frozen, attempting to assign to a property (with a setter or without) fails as expected:

from dataclasses import dataclass

@dataclass(frozen=True)
class Example:
	a: int

	@property
	def prop(self):
		return None

example = Example(10)
example.prop = 0
  File "test_dataclass.py", line 12, in <module>
    example.prop = 0
    ^^^^^^^^^^^^
  File "<string>", line 15, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'prop'

And when the class is slotted, if the property has no setter, it also fails the way one would expect:

from dataclasses import dataclass

@dataclass(slots=True)
class Example:
	a: int

	@property
	def prop(self):
		return None

example = Example(10)
example.prop = 0
Traceback (most recent call last):
  File "test_dataclass.py", line 12, in <module>
    example.prop = 0
    ^^^^^^^^^^^^
AttributeError: property 'prop' of 'Example' object has no setter

(In this case, of course, adding a setter makes it work fine.)

What's unexpected (and confusing) is when the class is both frozen and slotted:

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Example:
	a: int

	@property
	def prop(self):
		return None

example = Example(10)
example.prop = 0
Traceback (most recent call last):
  File "test_dataclass.py", line 12, in <module>
    example.prop = 0
    ^^^^^^^^^^^^
  File "<string>", line 16, in __setattr__
TypeError: super(type, obj): obj (instance of Example) is not an instance or subtype of type (Example).

One would, of course, expect an instance of Example to in fact be an instance of Example, but maybe this is somehow a collision between the initial vs. dataclass-ified class definitions?

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Linked PRs
  • gh-143971

贡献指南

打开贡献指南

从这里开始

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

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

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