Cannot infer type of lambda when using default arguments
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I get error: Cannot infer type of lambda even though the code seems fine to me.
Currently, I don't see any other workaround other than using # type: ignore.
To Reproduce
from typing import Callable, List
def foo(factories: List[Callable[[], int]]):
return sum(f() for f in factories)
names = ["0", "abc"]
# Inference works fine
assert foo([lambda: len(name) for name in names]) == 4
# Cannot infer type of lambda
assert foo([lambda name=name: len(name) for name in names]) == 4
def foo2(factories: List[Callable[[int], int]]):
return sum(f(0) for f in factories)
# Inference works fine
assert foo2([lambda i: len(name) for name in names]) == 4
# Cannot infer type of lambda
assert foo2([lambda i, name=name: len(name) for name in names]) == 4
Checked with:
mypy mypy-lambda-test.py
Expected Behavior
There should be no error. Especially because the other variants without default arguments are deemed fine.
Furthermore, using default arguments like this is the standard workaround to capture loop variables to lambdas.
Your Environment
- Mypy version used: 0.942
- Python version used: 3.9.7
- Operating system and version: Ubuntu 21.10
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the lambda examples in mypy-lambda-test.py and run mypy mypy-lambda-test.py using the reported Python and mypy versions. Compare the working lambdas with the variants that capture name through a default argument. Done means all four assertions type-check without requiring # type: ignore.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100