basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

Setting TYPE_CHECKING in an assignment expression makes code unreachable

Open roundedrectangle opened this issue 9 months ago • 2 comments

Description

Playground

if TYPE_CHECKING := False:
    pass

Code in this statement becomes unreachable. It is unreachable, in reality, but since it is for the variable TYPE_CHECKING type checker should think that it is reachable, which does not happen.

roundedrectangle avatar May 23 '25 15:05 roundedrectangle

TYPE_CHECKING needs to be imported from the typing module:

from typing import TYPE_CHECKING

if not TYPE_CHECKING:
    pass

See https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING

DetachHead avatar May 23 '25 21:05 DetachHead

Yes, but, setting the variable manually works too:

TYPE_CHECKING = False
if TYPE_CHECKING:
    pass # code is reachable

It also makes the code faster because importing typing module is not required

Using assignment expression, however, stops the same code from being reachable for type checker. Using it can make code easier to read if, for example, this statement is only used once.

roundedrectangle avatar May 24 '25 05:05 roundedrectangle

It happens in vanilla pyright, too. I created an issue on official pyright repository, but it got closed as not planned (by design). Should I close the issue on this repository too?

roundedrectangle avatar May 25 '25 15:05 roundedrectangle

The fact that most issues on pyright get closed "as designed" is the main reason I forked it in the first place, so I'll leave this open. If a regular assignment to TYPE_CHECKING works without having to import it from typing I don't see why it shouldn't also work with an assignment expression

DetachHead avatar May 25 '25 23:05 DetachHead