python / python/mypy

Unreachability should work for constrained type vars

Open
#19,256 1 comment 0 reactions 1 assignee View on GitHub

@tyralla is already working on this.

Since Jun 12, 2025.

feature topic-reachability topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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).

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.