Spurious type error using result of re.match in lambda inside map
Open
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
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 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