mypy doesn't take value restrictions into account when solving type variables
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
This came up in https://github.com/python/typeshed/pull/6762
from typing import Any, TypeVar, Union
T = TypeVar("T")
V = TypeVar("V", str, bytes)
def check_t(x: T | list[T]) -> T: ...
def check_v(x: V | list[V]) -> V: ...
x_str: str
x_list_any: list[Any]
x_str_list_any: str | list[Any]
# mypy does the correct thing here
reveal_type(check_t(x_str)) # str
reveal_type(check_t(x_list_any)) # list[Any] | Any
reveal_type(check_t(x_str_list_any)) # str | list[Any] | Any
reveal_type(check_v(x_str)) # str
# but maybe not here
# E: Value of type variable "V" of "check_v" cannot be "Union[List[Any], Any]"
# N: Revealed type is "Union[builtins.list[Any], Any]"
reveal_type(check_v(x_list_any))
# E: Value of type variable "V" of "check_v" cannot be "Union[str, List[Any], Any]"
# N: Revealed type is "Union[builtins.str, builtins.list[Any], Any]"
reveal_type(check_v(x_str_list_any))
Looking at the output, my guess is that mypy isn't taking value restrictions into account when solving constraints and only using value restriction as a check later. That is, list[Any] cannot match the T part of T | list[T] because it would violate the value restriction.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the supplied examples involving check_t, check_v, Any, and restricted TypeVars, then trace mypy's type-variable constraint solving and later value-restriction check. Done means the calls with list[Any] and str | list[Any] are accepted with appropriate revealed types, without the reported value-of-type-variable errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100