python / python/mypy

Unexpected used-before-def error when walrus operator is used to capture the matching item in an `any` comprehension

Open
#15,335 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.