Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
masasakano opened this issue Feb 7, 2020 · 4 comments
Labels
bug mypy got something wrong topic-pep-572 PEP 572 (walrus operator) topic-runtime-semantics mypy doesn't model runtime semantics correctly

Comments

@masasakano
Copy link

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

@dhood
Copy link
Contributor

dhood commented Jul 5, 2020

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

@hauntsaninja hauntsaninja added the topic-pep-572 PEP 572 (walrus operator) label Sep 25, 2020
@AlexWaygood AlexWaygood added bug mypy got something wrong topic-runtime-semantics mypy doesn't model runtime semantics correctly labels Apr 4, 2022
@bunny-therapist
Copy link

I just (2023) ran into this exact problem with

mypy 1.4.1 (compiled: yes)
Python 3.11.0

@it176131
Copy link

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

@JelleZijlstra
Copy link
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
Labels
bug mypy got something wrong topic-pep-572 PEP 572 (walrus operator) topic-runtime-semantics mypy doesn't model runtime semantics correctly
Projects
None yet
Development

No branches or pull requests

7 participants