Skip to content

TypedDict from compiled module causes KeyError for certain annotations #1075

@aatle

Description

@aatle

Bug report
Defining a TypedDict subclass with at least one annotation that includes an attribute access (e.g. collections.UserList) causes problems.
After successfully compiling the module with the TypedDict, the compiled module will raise KeyError: <...> upon importing the module (as it loads/executes the TypedDict subclass definition).

To reproduce
Create test.py file:

import collections
from typing import TypedDict

class MyDict(TypedDict):
    c: collections.deque

Compile test.py file:

mypyc test.py

Import/execute test.py file:

python -c "import test"

Result:

$ python -c "import test"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import test
  File "test.py", line 5, in <module>
    c: collections.deque
KeyError: 'deque'

NOTE:
Stringizing the annotation is a workaround and runs successfully:

class MyDict(TypedDict):
    c: 'collections.deque'

However, using from __future__ import annotations is NOT a workaround and results in the same error.

Environment
Mypy version used: 1.13.0 (compiled)
Mypy command-line flags: none
Mypy configuration options from mypy.ini (and other config files): none
Python version used: 3.13.0

EDIT
After trying to use the workaround, I realize that there are other possible annotations that have the bug.
If the TypedDict uses a non-generic type alias of generic type, then the bug also occurs.

Another case
# module.py (does not have to be compiled)
from typing import Generic, TypeVar

T = TypeVar('T')

class G(Generic[T]): pass

X = G[int]
# test.py
from typing import TypedDict
from module import X

class MyDict(TypedDict):
  c: X

Result:

$ python -c "import test"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import test
  File "test.py", line 6, in <module>
    c: X
KeyError: 'G'

So, the 'normalized'/expanded name of the annotation may be executed instead of the full, valid annotation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions