python / python/mypy

Class definition scope using walrus assignment operator raises [name-defined] error

Open
#16,347 1 comment 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

Bug Report

When using the assignment operator (aka "walrus") inside the class definition scope, I get a [name-defined] error.

To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=367470bba328790329e68ce08bd7eb59

class TestTuple:
    t = (a := 1, a)


class TestExpression:
    (b := 2, b)


def add(x: int, y: int):
    return x + y


class TestAdd:
    result = add(c := 3, c)


class TestOverride:
    d = add(d := 4, d)


TestTuple.a      # output: 1
TestTuple.t      # output: (1, 1)
TestExpression.b # output: 2
TestAdd.c        # output: 3
TestAdd.result   # output: 6
TestOverride.d   # output: 8

Expected Behavior
I expected mypy to not raise any error as these all execute in python.

Actual Behavior

main.py:2: error: Name "a" is not defined  [name-defined]
main.py:6: error: Name "b" is not defined  [name-defined]
main.py:14: error: Name "c" is not defined  [name-defined]
main.py:18: error: Name "d" is not defined  [name-defined]
Found 4 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.6.1
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11

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 with the linked mypy-play reproduction and the Python 3.11 examples in the issue, then trace how class-scope walrus assignments are analyzed. Done means the reported examples type-check without the four name-defined errors while preserving the shown inferred values.

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
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.