python / python/mypy

Mypy fails to resolve a less specific `TypeVar` in higher-order functions.

Open
#13,234 0 comments 0 reactions 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

Mypy fails to resolve a less specific TypeVar to a common subtype of arguments when in a higher-order function call.

For context: #22532

To Reproduce

(Example from @andersk)

from typing import Callable, TypeVar

T = TypeVar("T")
def f(g: Callable[[], T], x: T) -> T:
    return x

x: object = 1
y: object = f(object, x)  # ok
z: object = f(object, 1)  # error: Argument 1 to "f" has incompatible type "Type[object]"; expected "Callable[[], int]"

Expected Behavior

z: object = f(object, 1)

When resolving the arguments in f(object, 1), mypy should bind object to T. Given that the type of object (Callable[[], object]) is a subtype of Callable[[], object] and the type of 1 is a subtype of object, this should be accepted.

Actual Behavior

z: object = f(object, 1)  # error: Argument 1 to "f" has incompatible type "Type[object]"; expected "Callable[[], int]"

Instead of using the less specific object, mypy determines that T -> int and refuses to resolve it as object.

Your Environment

  • Mypy version used: 0.961
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): strict = true
  • Python version used: 3.8
  • Operating system and version: Ubuntu 20.04

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 provided higher-order function example with mypy 0.961, Python 3.8, and strict=true. Investigate how TypeVar inference handles the Callable and integer arguments, then verify that the call using object is accepted without the reported incompatibility error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.