Skip to content

Different behaviour for recursive TypedDict defined as class/functional #14460

@m0rl

Description

@m0rl

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions