Skip to content

BUILTINS is not a valid field name for a frozen dataclass #96151

Description

@hauntsaninja

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

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Aug 21, 2022
  2. added a commit that references this issue on Oct 10, 2022
  3. added a commit that references this issue on Oct 31, 2022
  4. added 2 commits that reference this issue on Oct 31, 2022
  5. added 2 commits that reference this issue on Oct 31, 2022
  6. ericvsmith commented on Oct 31, 2022

    @ericvsmith
    Member

    Merge and backports complete. Thanks, @hauntsaninja !

  7. added a commit that references this issue on Feb 18, 2023
  8. added a commit that references this issue on Mar 25, 2023
  9. added a commit that references this issue on Mar 27, 2023
  10. added a commit that references this issue on Apr 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions