Skip to content

The dataclasses unit tests should record behavior of shadowed init vars #119581

Closed

Description

@stroxler

Tests should verify that dataclasses allow no-default InitVars to use shadowed names.

I was surprised, when reviewing a change to MyPy that allows InitVar fields to be shadowed by property methods, that this even works since the runtime will drop the original InitVar value.

It turns out that __annotations__ does not forget about the original InitVar (__annotations__ preserves annotations from class attributes that came from assignment statements, ignoring any shadowing methods) and as a result this actually does work as long as no default value is provided.

See more discussion and context in python/mypy#17219.

@hauntsaninja mentioned that MyPy has had several reports of this as a false positives, so we know people are relying on this behavior (even if it may not have been intended originally) and we probably should not break it.

It probably makes sense to add a unit test, since this behavior is actually a bit surprising and could potentially be broken by a refactor. I'm not sure whether we should also discuss this in the documentation, I would lean toward "no" because I think this is supported more by accident than by design (both Pyright and Pyre reject it, which seems reasonable to me).

Linked PRs

Activity

  1. added 2 commits that reference this issue on May 26, 2024
  2. added
    testsTests in the Lib/test dir
    and removed
    docsDocumentation in the Doc dir
    on May 26, 2024
  3. added a commit that references this issue on May 28, 2024
  4. added 2 commits that reference this issue on May 28, 2024
  5. added 2 commits that reference this issue on May 28, 2024
  6. AlexWaygood commented on May 28, 2024

    @AlexWaygood
    Member

    Thanks @stroxler! I agree with adding a test, but not documenting it. It feels obscure enough that we probably shouldn't devote space to it; doing so might confuse new users just as much as it clarifies things for advanced users

  7. added a commit that references this issue on Jul 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    testsTests in the Lib/test dir

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions