python / python/mypy

Dict comprehensions fail in NamedTuple

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

Nobody has claimed this yet.

bug false-positive priority-1-normal semantic-analyzer topic-named-tuple
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

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 by reproducing the supplied NamedTuple and dict-comprehension example with the linked mypy-play configuration. Trace the type checker's handling of NamedTuple defaults and comprehension scope, then add a regression test; done means the example type-checks without the undefined-name errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.