-
-
Notifications
You must be signed in to change notification settings - Fork 30.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Dataclasses: frozen should not be inherited for non-dataclass derived classes #77134
Comments
Reported by Raymond Hettinger: When working on the docs for dataclasses, something unexpected came up. If a dataclass is specified to be frozen, that characteristic is inherited by subclasses which prevents them from assigning additional attributes: >>> @dataclass(frozen=True)
class D:
x: int = 10
>>> class S(D):
pass
>>> s = S()
>>> s.cached = True
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
s.cached = True
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/dataclasses.py", line 448, in _frozen_setattr
raise FrozenInstanceError(f'cannot assign to field {name!r}')
dataclasses.FrozenInstanceError: cannot assign to field 'cached' Other immutable classes in Python don't behave the same way: >>> class T(tuple):
pass
>>> class F(frozenset):
pass
>>> class B(bytes):
pass
Raymond |
A related issue is that dataclasses derived from frozen dataclasses are automatically "promoted" to being frozen. >>> @dataclass(frozen=True)
... class A:
... i: int
...
>>> @dataclass
... class B(A):
... j: int
...
>>> b = B(1, 2)
>>> b.j = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\home\eric\local\python\cpython\lib\dataclasses.py", line 452, in _frozen_setattr
raise FrozenInstanceError(f'cannot assign to field {name!r}')
dataclasses.FrozenInstanceError: cannot assign to field 'j' If this can't be addressed before 3.7, maybe it should be an error to declare B as non-frozen and then we can properly fix it in a future release. |
See https://mail.python.org/pipermail/python-dev/2018-February/152320.html for a discussion. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: