Skip to content

Walrus operators unrecognised in dictionary initialisation of a class attribute #8379

Open

Description

@masasakano

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).

Activity

  1. dhood commented on Jul 5, 2020

    @dhood
    Contributor

    This will also happen with a list e.g. l = [x2 := 1, x2 + 2, x2 + 3] (for this case also it will only happen if it is in the class scope).

    I have noticed, however, that it only happens on RE-USE of the variable from the assignment expression within the initialisation. Otherwise the walrus operator is ok.

    class Example:
        # l = [x2 := 1, x2 + 2, x2 + 3] # not OK
        l = [x2 := 1, 2, 3] # OK
    
  2. added
    topic-pep-572
    on Sep 25, 2020
  3. added
    bug
    topic-runtime-semantics
    on Apr 4, 2022
  4. bunny-therapist commented on Aug 19, 2023

    @bunny-therapist

    I just (2023) ran into this exact problem with

    mypy 1.4.1 (compiled: yes)
    Python 3.11.0
    
  5. it176131 commented on May 28, 2024

    @it176131

    Any proposed fix—besides # type: ignore[name-defined]—for this? I ran into it with the following versions:

    Python 3.12.2
    mypy   1.10.0
    
  6. JelleZijlstra commented on May 28, 2024

    @JelleZijlstra
    Member

    Anyone impacted should feel free to work on a PR to fix this. I haven't looked at the code but I imagine it's a relatively easy fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtopic-pep-572topic-runtime-semantics

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions