python / python/mypy

Function with generic class and generic value arguments are not inferred when generic is a TypedDict

Open
#19,201 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-typed-dict
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When defining a function expecting a generic class and a generic value — tied to the same TypeVar —, mypy is not able to infer the type of the argument if the generic type is a TypedDict.

It works well for scalar types, if the variable is explicitly defined as the typed dict type, or even more surprising, if the first generic argument is binded via a functools.partial.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=a6d36519fbd58e5c9b77999eedd16132

import typing
import functools

T = typing.TypeVar("T")


class A(typing.Generic[T]): ...


def f(a: A[T], t: T) -> None: ...


class D(typing.TypedDict):
    x: int


a_typed_dict = A[D]()
f(a_typed_dict, {"x": 1})  # error: Cannot infer type argument 1 of "f"  [misc]

Expected Behavior

The t argument is correctly validated as a D typed dict.

Actual Behavior

The following error message is returned:

error: Cannot infer type argument 1 of "f"  [misc]

Your Environment

  • Mypy version used: 1.15
  • Python version used: 3.12

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 linked mypy-play reproduction with mypy 1.15 and Python 3.12. Trace generic type inference for A[D] when validating the TypedDict argument; done means the call accepts {"x": 1} as D without the "Cannot infer type argument 1" 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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.