Skip to content

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

Closed
@stroxler

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

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