Skip to content
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

Improve error message for bound typevar in TypeAliasType #17053

Merged
merged 1 commit into from
Mar 28, 2024

Conversation

hamdanal
Copy link
Collaborator

Follow up to #17038

When a type variable is bound to a class, it cannot be reused in a type alias. Previously in TypeAliasType, this error was reported as "not included in type_params". However in the following example, the error is misleading:

from typing import Dict, Generic, TypeVar
from typing_extensions import TypeAliasType

T = TypeVar("T")


class A(Generic[T]):
    Ta11 = TypeAliasType("Ta11", Dict[str, T], type_params=(T,))


x: A.Ta11 = {"a": 1}
reveal_type(x)

On the master branch:

main.py:8: error: Type variable "T" is not included in type_params  [valid-type]
main.py:8: error: "T" is a type variable and only valid in type context  [misc]
main.py:8: error: Free type variable expected in type_params argument to TypeAliasType  [type-var]
main.py:12: note: Revealed type is "builtins.dict[builtins.str, Any]"
Found 3 errors in 1 file (checked 1 source file)

With this PR:

typealiastype.py:8: error: Can't use bound type variable "T" to define generic alias  [valid-type]
typealiastype.py:8: error: "T" is a type variable and only valid in type context  [misc]
typealiastype.py:12: note: Revealed type is "builtins.dict[builtins.str, Any]"
Found 2 errors in 1 file (checked 1 source file)

This is possible by storing the names of all the declared type_params, even those that are invalid, and checking if the offending type variables are in the list.

@hamdanal
Copy link
Collaborator Author

It would be nice to also get rid of the second remaining error, but this will require adding a special-cased context only for analyzing type_params and I am not comfortable doing this change without first consulting someone with more experience than me.

Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@JelleZijlstra JelleZijlstra self-requested a review March 21, 2024 02:00
@JelleZijlstra JelleZijlstra merged commit 337bcf9 into python:master Mar 28, 2024
18 checks passed
@hamdanal hamdanal deleted the typealiastype-class branch March 30, 2024 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants