python / python/mypy

Mypy fails to infer type parameters when composing generic functions with themselves

Open
#18,864 2 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 incorrectly infers Never types when the same generic function is used in multiple argument positions of a higher-order generic function, preventing proper composition of identical generic functions.

To Reproduce

from collections.abc import Callable

def compose[A, B, C](first: Callable[[A], B], second: Callable[[B], C]) -> Callable[[A], C]: ...

def id[T](value: T) -> list[T]: ...  # any generic would do

compose(id, id)
# Argument 1 to "compose" has incompatible type "Callable[[T], list[T]]"; expected "Callable[[Never], Never]"
# Argument 2 to "compose" has incompatible type "Callable[[T], list[T]]"; expected "Callable[[Never], Never]"

Expected Behavior

  1. The first id function should be inferred as Callable[[T], list[T]]
  2. The second id function should be inferred as Callable[[list[T]], list[list[T]]]
  3. The resulting composition should be Callable[[T], list[list[T]]]

Actual Behavior

Mypy fails to infer type parameters.

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.13

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 compose(id, id) example with mypy 1.15.0, Python 3.13, and --strict. Trace generic type inference for the two callable argument positions; done means the expected nested callable type is inferred without Never errors and a regression test covers the case.

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
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.