python / python/mypy

Add support for simple lambda type guard

Open
#9,890 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low topic-type-narrowing topic-typeguard-typeis
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

Consider the following code:

from typing import Optional, List


list_with_none: List[Optional[int]] = [None, 1, 2]


filtered = filter(lambda v: v is not None, list_with_none)
reveal_type(filtered)
# Revealed type is 'typing.Iterator[Union[builtins.int, None]]'

It would be nice if mypy was able to parse simple lambda functions like this one, and infer that filtered is typing.Iterator[builtins.int].

Note that in this example, we use a simple none check, but this could work with more complicated checks:

list_of_tuples: List[Tuple[Optional[int], Optional[int]]]
filter(lambda v: v[0] is not None and v[1] is not None, list_of_tuples)
# would become `Iterator[Tuple[int, int]]`

Pitch

This is a fairly common idiom in Python.

Reasons why mypy might now want to do this:

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 two filter/lambda examples and the PEP 647 reference; compare the requested revealed types and decide which simple predicates are in scope. Done means mypy infers Iterator[int] for the None-check example and Iterator[Tuple[int, int]] for the paired check, with coverage for the supported cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.