mypyc icon indicating copy to clipboard operation
mypyc copied to clipboard

TYPE_CHECKING block leads to "Reached allegedly unreachable code!"

Open kasium opened this issue 4 months ago • 2 comments

If a module contains a TYPE_CHECKING block, it can lead to a runtime error.

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    BaseDict = dict[Any, Any]
else:
    BaseDict = dict


class MyDict(BaseDict):
    pass

To reproduce

mypyc foo.py
python -c "import foo"

Error

Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import foo
  File "foo.py", line 8, in <module>
    BaseDict = dict
RuntimeError: Reached allegedly unreachable code!

kasium avatar Oct 31 '25 14:10 kasium

Hm, this is pretty bad, if TYPE_CHECKING: ... is a quite common pattern. I am surprised no one encountered this before. cc @JukkaL

ilevkivskyi avatar Nov 01 '25 20:11 ilevkivskyi

We should probably treat TYPE_CHECKING as False when running the code. However, the else block in the example hasn't been fully processed by mypy, so compiling it may be tricky.

JukkaL avatar Nov 04 '25 16:11 JukkaL