python / python/mypy

mypy doesn't take value restrictions into account when solving type variables

Open
#11,880 2 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

affects-typeshed bug topic-type-variables
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.