Skip to content

MyPy should report error if variable imported in TYPE_CHECKING block? #6104

Open
@sid-kap

Description

@sid-kap

Currently, MyPy doesn't report an error when a variable is imported in the if TYPE_CHECKING block and then used elsewhere.
For example, MyPy accepts this code:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import NamedTuple

class C(NamedTuple):
    x: int
    y: int

even though, at runtime, it fails:

Traceback (most recent call last):
  File "type_checking_test.py", line 6, in <module>
    class C(NamedTuple):
NameError: name 'NamedTuple' is not defined

(I'm using MyPy version 0.650.)

Should this be fixed? I think this could be fixed by adding an is_type_checking_only variable to SymbolTableNode, which is True if the variable was imported or assigned within a TYPE_CHECKING block, and ensuring that this flag is false for any variables used in places other than type annotations in the actual code.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions