Skip to content

Cyclic errors with forward refs in TypeVar default and bound #20829

@peacefulotter

Description

@peacefulotter

Bug Report

Using typing_extensions.TypeVar(..., default="SomeClass") with a stringified forward reference to a generic defined later in the file produces:

  • Cannot resolve name "Bar" (possible cyclic definition)
  • TypeVar "default" must be a type

However, Pylance and reveal_type are still able to infer the expected types, as demonstrated by the example below.

To Reproduce

from abc import ABC, abstractmethod
from typing import Any, Generic

from typing_extensions import TypeVar, reveal_type

# ---- Defining Foo

BarT = TypeVar("BarT", default="Bar[Any]", bound="Bar[Any]")

class Foo(ABC, Generic[BarT]):
    @abstractmethod
    def to_bar(self) -> BarT: ...

class MyFoo(Foo["MyBar"]):
    def to_bar(self) -> "MyBar":
        return MyBar(self)

# ---- Defining Bar

FooT = TypeVar("FooT", default=Foo[Any], bound=Foo[Any])

class Bar(Generic[FooT]):
    def __init__(self, foo: FooT) -> None:
        self.foo = foo

class MyBar(Bar[MyFoo]):
    pass

bar = MyFoo().to_bar()
reveal_type(bar)
reveal_type(bar.foo)

Expected Behavior

Accept default="Bar[Any]" and bound="Bar[Any]" as a valid forward reference and do not emit the cyclic-definition / “default must be a type” errors.

Actual Behavior

main.py:8: error: Cannot resolve name "Bar" (possible cyclic definition)  [misc]
main.py:8: error: TypeVar "default" must be a type  [misc]
main.py:8: error: TypeVar "bound" must be a type  [misc]
main.py:16: error: Cannot resolve name "MyBar" (possible cyclic definition)  [misc]
main.py:34: note: Revealed type is "main.MyBar"
main.py:35: note: Revealed type is "main.MyFoo"

Your Environment

  • Mypy version used: 1.19.1
  • Mypy command-line flags: /
  • Mypy configuration options from mypy.ini (and other config files): /
  • Python version used: 3.10.6 & 3.14.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions