Skip to content

Default value for Generic self is erased by @dataclass #14382

Closed as not planned
Closed as not planned
@zmievsa

Description

@zmievsa

Note that pyright has a similar behavior so I am not sure whether it is a bug per se but I do believe that it is an incorrect behavior.

Bug Report

It is possible to specify the default value for a generic self using __init__ parameter type hint or __new__ return type hint. However, when a @dataclass decorator is applied to the class and when it generates __init__, the __new__ definition gets erased.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=13b4e50085788299b532d56cf70c3eb8

Expected Behavior
Mypy must show:

main.py:22: note: Revealed type is "__main__.User[Literal['NotLoggedIn']]"

And it does show it if the @dataclass gets commented out, init=False is passed to the dataclass, or if the following __init__ is added to the class:

def __init__(self: "User[Literal['NotLoggedIn']]", name: str) -> None:
    self.name = name

Actual Behavior

main.py:21: error: Need type annotation for "f"  [var-annotated]
main.py:22: note: Revealed type is "__main__.User[Any]"

Your Environment

  • Mypy version used: 0.991
  • Python version used: 3.11

Relevant links

#4236

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions