python / python/mypy

NamedTuple with dependent default values causes unexpected 'Name is not defined' errors

Open
#8,178 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hi there,

When there is a NamedTuple with a default value that depends on one or more other default values, followed by a default value that should resolve into a NameError, all preceding default values get the Name <variable> is not defined error as well.

E.g.

from typing import NamedTuple

class Example(NamedTuple):
    a: int = 1
    b: int = 2
    c: int = a*b
    d: int = does_not_exist*5

Causes:

scratch.py:6: error: Name 'a' is not defined
scratch.py:6: error: Name 'b' is not defined
scratch.py:7: error: Name 'does_not_exist' is not defined

If I comment out line 6, I do, however, get the expected result.

from typing import NamedTuple

class Example(NamedTuple):
    a: int = 1
    b: int = 2
    # c: int = a*b
    d: int = does_not_exist*5
scratch.py:7: error: Name 'does_not_exist' is not defined

This was tried on version 0.760.

$ mypy --version
mypy 0.760

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 issue from the scratch.py NamedTuple example using mypy 0.760, then inspect the NamedTuple type-checking path responsible for default values. Compare the dependent-default case with the version where c is commented out. Done means the undefined name in d is reported without spurious errors for a, b, or c.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.