python / python/mypy

Walrus operators unrecognised in dictionary initialisation of a class attribute

Open
#8,379 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

It seems Walrus operators (in Python 3.8+) are not recognised by mypy when used in initialising a dictionary of a class attribute. Here is a test code.

class TryWalrus:
    CKEY = { 
        'KY': (p:='a_'),
         'ANOTHER': p+'content',
        }

print(TryWalrus.CKEY['ANOTHER']) # => a_content

This outputs the following:

$ mypy try_walrus.py
try_walrus.py:4: error: Name 'p' is not defined
Found 1 error in 1 file (checked 1 source file)

If the variable CKEY is out of the class definition, i.e. if directly in Main, it does not raise an error.

I tested it with Python 3.8.1 and mypy version 0.770+dev.8888b1aedf6d4ba543ae12f538f190ce5e65c20d (yesterday's head).

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 reproducer in try_walrus.py and run mypy against it using the class-level dictionary shown in the report. Trace how walrus assignments are processed inside class attribute initialisation, then confirm that the valid Python 3.8 example no longer reports Name 'p' as undefined.

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.