python / python/mypy

Lambda type cannot be inferred when type context includes a callable with a callable parameter

Open
#16,523 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

This was filed as a pyright bug. I noticed that mypy likewise doesn't handle this case, and I couldn't find any open issues that cover this.

Mypy playground link

from typing import Callable, Generic, TypeVar

T = TypeVar("T")

def func1(callable: Callable[[Callable[[T], T]], T]) -> T:
    return callable(lambda x: x)

v1 = func1(lambda a: a(0))
reveal_type(v1)  # Should be int

v2 = func1(lambda a: a(""))
reveal_type(v2)  # should be str

class A(Generic[T]):
    def __init__(self, value: T) -> None:
        self.value = value

def func2(callable: Callable[[type[A[T]]], A[T]]) -> T:
    return callable(A).value

v3 = func2(lambda A: A(0))
reveal_type(v3)  # Should be int

v4 = func2(lambda A: A(""))
reveal_type(v4)  # Should be str

Expected Results: No Errors and revealed types as indicated in the comments

Actual Results: Multiple errors ("Need type annotation for ...").

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 linked mypy playground and run the included Python reproducer involving Callable, Generic, and TypeVar. Compare the revealed types for v1 through v4 with the expected int and str results; done means the examples produce no errors and reveal those types.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.