python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.26k stars 2.79k forks source link

`TYPE_CHECKING` doesn't work if imported with alias #12928

Open DetachHead opened 2 years ago

DetachHead commented 2 years ago
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING as amogus

if not TYPE_CHECKING:
    1 + "" # no error (unreachable)

if not amogus:
    1 + "" # error

playground

DetachHead commented 2 years ago

it also doesn't care if i define a fake TYPE_CHECKING variable

TYPE_CHECKING = False

if not TYPE_CHECKING:
    1 + "" # no error even though this is reachable at runtime
KotlinIsland commented 2 years ago

I think there is an impostor among us image

pranavrajpal commented 2 years ago

it also doesn't care if i define a fake TYPE_CHECKING variable

I think that's probably a remnant of when you couldn't import TYPE_CHECKING (or MYPY, which was an earlier version of the same thing) from typing so defining a False constant with the right name was the recommended usage (see the first example in #308).

That behavior could be considered a feature if you wanted to be able to add types to Python 2 code without having to install the typing backport, but, judging from #12237, we're probably fine making breaking changes for Python 2 users.