python / mypy

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

Mypyc crashes on conditionally-defined class #15716

Open nickdrozd opened 1 year ago

nickdrozd commented 1 year ago

To Reproduce

if True:
    class A:
        pass

(This example is silly, but a real use case would be defining a protocol inside a TYPE_CHECKING block.)

Actual Behavior

  File "mypy/mypy/nodes.py", line 1141, in accept
    return visitor.visit_class_def(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "mypy/mypyc/irbuild/visitor.py", line 167, in visit_class_def
    transform_class_def(self.builder, cdef)
  File "mypy/mypyc/irbuild/classdef.py", line 88, in transform_class_def
    ir = builder.mapper.type_to_ir[cdef.info]
         ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
asdf.py:2: KeyError: <TypeInfo asdf.A>
mypyc --version
mypy 1.6.0+dev.89ad125fa5a31a7c82f267e957d3c94da6b52f61
(compiled: no)
nickdrozd commented 1 year ago

Similar in spirit to https://github.com/python/mypy/issues/13613

nickdrozd commented 1 year ago

The stack trace makes it look like the problem is just with building the class mapping incorrectly. That can be fixed easily, but beyond that there is also a codegen problem that is not so straightforward.

guywilsonjr commented 4 months ago

For anyone following According to https://mypyc.readthedocs.io/en/latest/differences_from_python.html#conditional-functions-or-classes:

Function and class definitions guarded by an if-statement are not supported.
JelleZijlstra commented 4 months ago

Even if it's unsupported, mypy should show a clear error message instead of crashing. A crash is always a bug.