Skip to content

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

Open
@alexcoplan

Description

@alexcoplan

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions