Skip to content
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

Dict comprehensions fail in NamedTuple #8376

Open
edward-io opened this issue Feb 6, 2020 · 4 comments
Open

Dict comprehensions fail in NamedTuple #8376

edward-io opened this issue Feb 6, 2020 · 4 comments
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal semantic-analyzer Problems that happen during semantic analysis topic-named-tuple

Comments

@edward-io
Copy link

from typing import Dict, Any, NamedTuple

def out() -> str:
    return "out"

d = {"x": 0, "y": 1}

class Test(NamedTuple):
    qwer: Dict[str, Any] = {k: v for k, v in d}

Fails mypy with error:

main.py:13: error: Name 'k' is not defined
main.py:13: error: Name 'v' is not defined
Found 2 errors in 1 file (checked 1 source file)

Oddly, removing the out function makes type checking work again:

from typing import Dict, Any, NamedTuple


d = {"x": 0, "y": 1}


class Test(NamedTuple):
    qwer: Dict[str, Any] = {k: v for k, v in d}
Success: no issues found in 1 source file

Playground URL: https://mypy-play.net/?mypy=latest&python=3.8&gist=aa715bc0f6d14152487d753f3fa64885

@edward-io edward-io changed the title Dict comprehensions fail to find variables in NamedTuple Dict comprehensions fail in NamedTuple Feb 6, 2020
@msullivan msullivan added bug mypy got something wrong false-positive mypy gave an error on correct code semantic-analyzer Problems that happen during semantic analysis priority-1-normal labels Feb 10, 2020
@msullivan
Copy link
Collaborator

Moving out below the namedtuple also makes it work. That is deeply weird.

Some semantic analyzer weirdness I think.

@Arshaan-256
Copy link

The check is actually supposed to fail right? Can I work on this?

@edward-io
Copy link
Author

@Arshaan-256 The check should succeed, I believe. All the code is valid Python and the types look correct.

@JelleZijlstra
Copy link
Member

Still reproduces, and I agree with Sully that this is really weird.

Note that the code sample has a typo: it should be for k, v in d.items().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal semantic-analyzer Problems that happen during semantic analysis topic-named-tuple
Projects
None yet
Development

No branches or pull requests

4 participants