Unreachability should work for constrained type vars
Feature
Unreachability should be checked for constrained type vars.
Pitch
It would be nice if this raised an error when run with --warn-unreachable:
from typing import TypeVar
U = TypeVar('U', int, str)
def f(u: U) -> U:
if u is None:
print("whoa!!")
return u
To implement this feature, I think we need to store the spans of unreachability for each run, then find the intersection. I thought for a while that we could just treat constrained type variables as if they were bound to the union of constraints, but things like https://github.com/python/mypy/issues/9424 will happen for things that aren't final (unlike None).
I investigated a little, and this limitation seems to have been known for a while:
https://github.com/python/mypy/blob/8241059c14f99ad750ae3ac0de6a4795bf990f61/test-data/unit/check-unreachable-code.test#L1036-L1049
https://github.com/python/mypy/blob/8241059c14f99ad750ae3ac0de6a4795bf990f61/mypy/checker.py#L1467-L1475
I experimented with the IterationErrorWatcher proposed in #19270 and was successful in the first simple attempt. However, as many existing tests would require adjustment and some new ones should be introduced (which might reveal the need to adjust the method eventually), I will wait to work on it until #19270 is accepted.
By the way, aren't classes with type variables with value constraints a problem, too?