python / python/mypy

Incorrect type narrowing for `x in y` pattern when `x` is `type[T]` and `y` is an iterable of class objects

Open
#17,728 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

As the title suggests, if one uses the type_var in (type1, type2, ...) construct instead of issubtype(type_var, (type1, type2, ...), and type_var is generic, mypy struggles with narrowing down the type.

The same bug happens in pyright.

To Reproduce

from typing import TypeVar

T = TypeVar('T')

def func(typ: type[T], input: str) -> T:
    if typ in (str, int, float):
        return typ(input) # error: Too many arguments for "object"  [call-arg]
    else:
        raise ValueError() # Just for the sake of demonstration

def func(typ: type[T], input: str) -> T:
    if issubclass(typ, (str, int, float)):
        return typ(input) # No problem!
    else:
        raise ValueError() # Just for the sake of demonstration

Playground URL

Expected Behavior

Both versions of the type check act the same.

Actual Behavior
Mypy incorrectly throws Too many arguments for "object" [call-arg] error.

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12 / 3.10

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 reproducer with mypy and compare the in and issubclass cases. Trace the type-narrowing path for membership checks and add a regression test covering type[T] with an iterable of class objects; done means the typ(input) call is accepted in the in case without weakening the existing behavior.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.