python / python/mypy

Error for lambda containing Any even when type can be inferred

Open
#5,879 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-0-high topic-disallow-any topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Using mypy 0.641 with the --disallow-any-expr flag and this sample using @overload

from typing import Callable, Tuple, TypeVar, overload

T = TypeVar('T')
A0 = TypeVar('A0')
A1 = TypeVar('A1')


@overload
def foo(
    vars: Tuple[A0],
    op: Callable[[A0], T]
) -> T: ...


@overload
def foo(
    vars: Tuple[A0, A1],
    op: Callable[[A0, A1], T]
) -> T: ...


def foo(vars, op):
    pass


def foo_not_overloaded(
    vars: Tuple[A0, A1],
    op: Callable[[A0, A1], T]
) -> T:
    pass


a = 5
b = 3

foo((a, b), lambda a, b: a - b)

produces

typist2.py:36: error: Expression type contains "Any" (has type "Callable[[Any, Any], Any]")
typist2.py:36: error: Expression has type "Any"

However mypy seems to be able to infer the type of the lambda because if I modify the last line to read

foo((a, b), lambda a, b: a - b.bad)

mypy correctly identifies that "int" has no attribute "bad", sprinkling some prints on the mypy source also reveals it figures out it's a (int, int) -> int at some point.

foo_not_overloaded checks without trouble and so does using a plain def instead of the lambda.

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 supplied reproducer using mypy 0.641 and compare the overloaded foo call with foo_not_overloaded and the plain def case. Trace the lambda's inferred type through the overload path, then verify that the valid lambda no longer triggers disallow-any-expr errors while the a - b.bad variant still reports the invalid attribute.

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.