-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Type aliases in class definitions #9238
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
Comments
Yeah that doc section you linked is incomplete. The PR that added it closed the relevant issue but didn't address all points, in particular the special case about plain names at class scope creating variables. cc @TH3CHARLie Btw the fix is simply to use: class ABC:
ABCInputType = List[Any] |
What causes |
A trick that should work if you want to force type alias for plain name at class scope is use a single element union. |
I did recall that when doing the docs PR we did mention about the alias should appear at top level but somehow I must have forgotten to include that in the final version. I'll file a PR to fix that. |
The problem as stated in the issue above is solved now with PEP 613: from typing import List, TypeAlias
class ABC:
ABCInputType: TypeAlias = List
x: ABC.ABCInputType = [] -> no errors However, this does not work in dataclasses (or any dataclass-like class), where you have to use from dataclasses import dataclass
from typing import ClassVar, List, TypeAlias
@dataclass
class ABC:
ABCInputType: ClassVar[TypeAlias] = List
x: ABC.ABCInputType = []
reveal_type(x) # Revealed type is "Any" There's no error in mypy 0.942, but it thinks the type of |
Thanks! I'm closing this now since the original issue is now solved for most cases. Please feel free to open a new issue for the dataclasses- specific issue. |
Under MyPy 0.780, the code
throws
while
works just fine.
The use of type aliases in classes seems both like a pretty legitimate use case to me (consider for example the ability to have an input type for the class as an attribute of the class as above) and also seems consistent with both the
typing
documentation andmypy
's documentation, neither of which seem to mention that type aliases can only appear at the top level (only that they need to be plain assignments, as they are in the above code).The text was updated successfully, but these errors were encountered: