KEMBAR78
Support `TypeAliasType` in a class scope by hamdanal · Pull Request #17038 · python/mypy · GitHub
Skip to content

Conversation

hamdanal
Copy link
Collaborator

@hamdanal
Copy link
Collaborator Author

There is also the question of whether to explicitly disallow aliases in a function scope but mypy currently allows PEP 613 TypeAlias within functions (see #16614 (comment)) so I think both cases should be considered together.

@github-actions
Copy link
Contributor

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

@JelleZijlstra JelleZijlstra merged commit b013cc0 into python:master Mar 16, 2024
@hamdanal hamdanal deleted the class-typealiastype branch March 16, 2024 16:11
JelleZijlstra pushed a commit that referenced this pull request Mar 28, 2024
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:
```python
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.
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.

Add support for TypeAliasType

2 participants