python / python/mypy

Cannot infer type argument with TypeVarTuple and Callback protocol

Open
#17,453 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-pep-646 topic-protocols
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

To Reproduce

# mypy: enable-incomplete-feature=NewGenericSyntax
from collections.abc import Callable
from typing import Protocol

class ActionType(Protocol):
    def __call__(self, var: str, context: int = 2) -> None: ...

class Job[*_Ts]:
    def __init__(self, target: Callable[[*_Ts], None]) -> None:
        self.target = target

def run_job[*_Ts](job: Job[*_Ts], *args: *_Ts) -> None: ...

def a1(action: ActionType) -> None:
    job = Job(action)
    run_job(job, "Hello")  # -> error

Actual Behavior

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

Expected Behavior
No error. Mypy should be able to tell that context has a default value and is thus optional. It already works from pure Callables (without the intermediate generic class).

def run_job_2[*_Ts](action: Callable[[*_Ts], None], *args: *_Ts) -> None: ...

def a2(action: ActionType) -> None:
    run_job_2(action, "Hello")  # works fine

Your Environment

  • Mypy version used: mypy 1.11.0+dev.177c8ee7b8166b3dcf89c034a676ef5818edbc38 (compiled: no) (current master)
  • Mypy command-line flags: --enable-incomplete-feature=NewGenericSyntax (the bug exists with the old generic syntax as well)
  • 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 with the reproducer and compare the failing run_job path with the working run_job_2 example under Python 3.12 and the NewGenericSyntax flag. Trace type inference for TypeVarTuple through Job and the ActionType callback; done means the first example infers its arguments without an error while existing behavior remains intact.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.