Skip to content

Unexpected behavior with dataclasses and weakref #102069

Description

@jbaudisch

We recently discovered the following error in our project:
TypeError: descriptor '__weakref__' for 'XYZ' objects doesn't apply to a 'XYZ' object

XYZ in our case is a dataclass which uses slots (added v3.10) and weakref_slot (added v3.11) parameters.

We further investigated the error and have come to the following example to reproduce it:

import dataclasses
import weakref


@dataclasses.dataclass(slots=True, weakref_slot=True)
class EntityAsDataclass:
    x: int = 10


class Entity:
    __slots__ = ("x", "__weakref__")

    def __init__(self, x: int = 10) -> None:
        self.x = x


e1 = Entity()
e1_ref = weakref.ref(e1)

e2 = EntityAsDataclass()
e2_ref = weakref.ref(e2)


assert e1.__weakref__ is e1_ref  # works
assert e2.__weakref__ is e2_ref  # fails with "TypeError: descriptor '__weakref__' for 'EntityAsDataclass' objects doesn't apply to a 'EntityAsDataclass' object"

I don't know if this is intended, but we expect EntityAsDataclass and Entity to have the same behavior here.

Thanks!

Linked PRs

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    3.11only security fixes
    on Feb 20, 2023
  2. self-assigned this
    on Feb 20, 2023
  3. sobolevn commented on Feb 20, 2023

    @sobolevn
    Member

    I know how to fix it! Thanks for the report! PR is on its way.

  4. added a commit that references this issue on Feb 20, 2023
  5. added a commit that references this issue on Mar 13, 2023
  6. added a commit that references this issue on Mar 13, 2023
  7. added a commit that references this issue on Mar 13, 2023
  8. added a commit that references this issue on Mar 14, 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

3.11only security fixesstdlibStandard 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