python / python/mypy

Spurious type error using result of re.match in lambda inside map

Open
#18,947 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Consider the following testcase:

import re
r = re.compile("([a-z]+)")
if m := re.match(r, "abc"):
  matches = map(lambda i: m.group(i), [1])
  print(next(matches))

I expect this to pass type checking successfully, but mypy instead complains about the map line as follows:

mypy ./t.py
t.py:4: error: Item "None" of "Match[str] | None" has no attribute "group"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

The bug only seems to happen if the lambda appears directly inside the call to map. E.g. if I pre-declare it as follows:

import re
r = re.compile("([a-z]+)")
if m := re.match(r, "abc"):
  fn = lambda i: m.group(i)
  matches = map(fn, [1])
  print(next(matches))

then this type-checks OK. My environment is as follows:

$ mypy --version
mypy 1.15.0 (compiled: yes)
$ python3 --version
Python 3.13.2

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 testcase and run mypy 1.15.0 on Python 3.13.2, comparing the inline lambda passed to map with the separately assigned lambda. Done means the inline form type-checks without the reported union-attr error while preserving the existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.