You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUILTINS is not a valid field name for a frozen dataclass #96151
This is not a bug that I encountered in the wild, but I happened to notice the possibility for this while reading the source.
from dataclasses import dataclass
@dataclass(frozen=True)
class X:
BUILTINS: str
X(5)
will give you:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 3, in __init__
AttributeError: 'int' object has no attribute 'object'
There are other field names that you can use to trick dataclass into bad behaviour, but all of the other ones are prefixed by an underscore.
So one "fix" is pretty simple: just rename BUILTINS to _BUILTINS in dataclasses.py to bring it in line with the others.
If a single underscore doesn't feel like sufficient "this is the user's fault", we could use __dataclass_* (like we do for __dataclass_self__ param to __init__)
For what it's worth, the only thing we need BUILTINS for is so we can access object inside __init__, so an alternative fix could be to use ().__class__.__base__ instead of BUILTINS.object (and skip the locals dance needed to define BUILTINS altogether)
If any of that sounds worth doing, I'd be happy to open a PR
Activity
pythongh-96151: Use a private name for passing builtins to dataclass
gh-96151: Use a private name for passing builtins to dataclass. This …
pythongh-96151: Use a private name for passing builtins to dataclass.…
pythongh-96151: Use a private name for passing builtins to dataclass.…
[3.10] gh-96151: Use a private name for passing builtins to dataclass…
[3.11] gh-96151: Use a private name for passing builtins to dataclass…
ericvsmith commentedon Oct 31, 2022
Merge and backports complete. Thanks, @hauntsaninja !
pythongh-98886: Fix issues with fields with special underscore names
gh-98886: Fix issues with dataclass fields with special underscore na…
pythongh-98886: Fix issues with dataclass fields with special undersc…
pythongh-98886: Fix issues with dataclass fields with special undersc…