python / python/mypy

redundant-expr does not work with TypeVar with multiple constraints

Open
#18,434 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report
A TypeVar with multiple constraints can be seen as a union. However, the redundant-expr does not understand it and emits errors which are wrong.

To Reproduce

from typing import TypeVar

T = TypeVar("T", int, str)

def foo(var: T) -> T:
    return "aa" if isinstance(var, str) else 0

Expected Behavior

no error

Actual Behavior

foo.py:9:20: error: If condition is always false  [redundant-expr]
        return "aa" if isinstance(var, str) else 0
                       ^~~~~~~~~~~~~~~~~~~~
foo.py:9:20: error: If condition is always true  [redundant-expr]
        return "aa" if isinstance(var, str) else 0
                       ^~~~~~~~~~~~~~~~~~~~
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.14.1
  • Mypy command-line flags: --enable-error-code redundant-expr
  • Python version used: 3.13.0

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 running the provided TypeVar example with mypy 1.14.1 and --enable-error-code redundant-expr. Trace the redundant-expr analysis for constrained TypeVars, then add a regression test showing that the isinstance check produces no error and run the relevant test suite.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.