Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
m0rl opened this issue Jan 16, 2023 · 0 comments · Fixed by #14488
Closed

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

m0rl opened this issue Jan 16, 2023 · 0 comments · Fixed by #14488
Labels
bug mypy got something wrong topic-recursive-types

Comments

@m0rl
Copy link

m0rl commented Jan 16, 2023

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 m0rl added the bug mypy got something wrong label Jan 16, 2023
JukkaL pushed a commit that referenced this issue Jan 21, 2023
Fixes #14460

Recursive TypedDicts/NamedTuples defined with call syntax that have item
types that look like type applications suffer the same chicken-and-egg
problem that recursive type aliases. Fortunately, there is a very simple
way to distinguish them without fully analyzing rvalues, this is what
this PR does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-recursive-types
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants