python / python/mypy

False positive on function call with walrus operator

Open
#17,377 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-pep-572
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In our codebase we chose specific way of working with pytest.mark.parametrize.
It is hard to look at tests which names are autogenerated from parameters list. To improve this we use parametrize(ids=) argument.
Unfortunately maintainability/readability of tests decreases if test cases and ids are written separately.
To resolve this issue we add some description to test cases and reuse it in ids with walrus operator.
For instance

class TestA:
    @pytest.mark.parametrize(
        'desc,a,b',
        _test_cases := (('a != b', 1, 2),), 
        ids=[desc for desc, *_ in _test_cases],
    )
    def test_func(self, desc: str, a: int, b: int) -> None:
        assert a == b, desc

Mypy says here that _test_cases does not exist which is incorrect

To Reproduce

I have created simple playground without pytest dependency to reproduce the error
https://mypy-play.net/?mypy=master&python=3.12&flags=check-untyped-defs&gist=8f98cbc918fbf8053a14f58c8011e375

Expected Behavior

Success: no issues found in 1 source file

Actual Behavior

main.py:11: error: Name "my_call_vars" is not defined [name-defined]

Your Environment

  • Mypy version used: 1.10.0 and master
  • Mypy command-line flags: no specific flags needed
  • Mypy configuration options from mypy.ini (and other config files): no specific configurations
  • Python version used: 3.10, 3.12

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 by running the linked mypy-play reproduction for main.py with the stated Python versions and flags. Trace how the walrus assignment and subsequent function-call comprehension are analyzed, then add coverage for this example. Done means the reproduction reports “Success: no issues found in 1 source file” without the name-defined error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.