mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Different behaviour for recursive TypedDict defined as class/functional

Open m0rl opened this issue 2 years ago • 0 comments

Bug Report

TypedDict-based recursive type is flagged as invalid when defined using functional syntax while no issue is reported for analogous class-based definition.

To Reproduce

from typing import List, TypedDict

Example = TypedDict("Example", {"rec": List["Example"]})

Expected Behavior

TypedDict-based recursive types to have similar behaviour when defined using class/functional syntax.

Actual Behavior

from typing import List, TypedDict

Example = TypedDict("Example", {"rec": List["Example"]})

results in an error:

Cannot resolve name "Example" (possible cyclic definition)

while similar type defined as a class has no issues reported:

from typing import List, TypedDict

class Example(TypedDict):
    rec: List["Example"]

Also no issue is reported when the recursive property is defined using some of the special forms (like Required, Optional etc) instead of List. The following code passes typecheck without errors:

from typing import Optional, TypedDict

Example = TypedDict("Example", {"rec": Optional["Example"]})

Your Environment

  • Mypy version used: mypy 0.991 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.1

m0rl avatar Jan 16 '23 18:01 m0rl