python / python/mypy

“Cannot infer type of lambda” using default parameter to recapture loop variable

Open
#15,459 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

One of the most common gotchas in Python is that a loop reassigns its iteration variable rather than creating a new binding for each iteration, and a lambda closure created in the loop observes this reassigned value rather than the value from each iteration. A typical workaround is to add a “redundant” default parameter to the lambda to recapture the value from each iteration—for example, the i=i from the above link (reproduced below). But mypy rejects such a lambda with error: Cannot infer type of lambda [misc].

To Reproduce

from typing import Callable

def create_multipliers() -> list[Callable[[int], int]]:
    return [lambda x, i=i: i * x for i in range(5)]

(mypy playground)

Expected Behavior

mypy ought to be able to realize that since the lambda is coerced to Callable[[int], int], its second parameter i=i can only ever receive the default value, so its type should be successfully inferred as (x: int, i: int = ...) -> int.

Actual Behavior

main.py:4: error: Cannot infer type of lambda  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

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

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 main.py reproduction with mypy and reviewing how lambda parameter and default-expression types are inferred for the Callable[[int], int] context. Trace the relevant type-inference entry point and add a regression test for the example; done means mypy accepts the code without Cannot infer type of lambda while preserving the inferred callable signature.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.