-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Default value for Generic self is erased by @dataclass #14382
Comments
FWIW, I closed this issue in the pyright issue tracker because I don't consider this a bug in pyright. The mechanism by which a constructor's specialized type is influenced by an annotated |
@erictraut do I understand correctly that your work with @JelleZijlstra on PEP 696 is supposed to solve this issue in its entirety? |
@Ovsyanka83, no, this issue has nothing to do with PEP 696 (or PEP 695). |
@erictraut I decided to go back and check whether I'll be able to use typevardefaults with the latest pyright and succeeded. And it does solve my problem in its entirety. Take a look at the modified code that reveals the expected type: from dataclasses import dataclass
from typing import Generic, TypeVar, cast
from typing_extensions import TYPE_CHECKING, Literal
if TYPE_CHECKING:
T = TypeVar("T", bound=Literal["LoggedIn", "NotLoggedIn"], default=Literal["NotLoggedIn"])
@dataclass
class User(Generic[T]):
name: str
def log_in(self) -> "User[Literal['LoggedIn']]":
return cast(User[Literal["LoggedIn"]], self)
def scream(self: "User[Literal['LoggedIn']]") -> None:
print(f"{self.name} screams!")
f = User("admin")
reveal_type(f) I apologize for disturbing you and I am really grateful for your work on PEP 696 in pyright. |
(Also, to be clear, PEP 696 is @Gobot1234's work, not mine; I am just the PEP sponsor.) |
Closing in favour of whatever issue is tracking 696 |
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:
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:Actual Behavior
Your Environment
Relevant links
#4236
The text was updated successfully, but these errors were encountered: