Unexpected used-before-def error when walrus operator is used to capture the matching item in an `any` comprehension
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
mypy returns an unexpected used-before-def error when a walrus operator is used to capture the matching element in an any comprehension.
Given test_mypy.py containing:
test = ['a', 'b', 'c']
if any((_t := itm) == 'c' for itm in test):
print(f'{_t=}')
else:
_t = None
print(_t)
mypy produces:
>mypy test_mypy.py
test_mypy.py:3: error: Name "_t" is used before definition [used-before-def]
Found 1 error in 1 file (checked 1 source file)
Let me know if this is captured elsewhere in list of walrus operator issues, or if it's not a problem for some reason I'm not seeing. Thanks!
mypy==1.3.0
python==3.10.4
no cmd line options outside of the test file name.
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
Reproduce the report with the example in test_mypy.py using mypy with no options beyond the filename. Trace how the type checker handles the walrus assignment inside the any comprehension, then add a regression test showing the diagnostic is no longer emitted for the reported pattern.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100