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

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

Open
sndrtj opened this issue Dec 19, 2019 · 1 comment

Comments

@sndrtj
Copy link

sndrtj commented Dec 19, 2019

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
@ilevkivskyi
Copy link
Member

Named tuple class bodies are special-cased in mypy. In particular, the assignment r.h.s. are default values in constructors, not more than that. I think it may make sense to support this, since one would naturally expect this to work (and the error message is unclear).

A possible downside is that if we allow this, people might expect that such assignment will cause default value for c to be dynamically calculated, i.e., that Example(3, 5).c is 15, while in fact it is 2.

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

No branches or pull requests

2 participants