Skip to content

Forward-referencing type application with type variable in a value expression in stubs emits confusing error #19601

@bzoracler

Description

@bzoracler

Bug Report, To Reproduce, & Actual Behaviour

In .pyi stub files, the spec mandates type-checkers to recognise forward references in annotation expressions without string-quoting. It is however silent about value expressions, but in mypy I've used symbols defined later in a stub file in a value context before without any issues, except recently when hitting the following example:

# stub.pyi
from typing_extensions import Generic, TypeVar

R = TypeVar("R")
T = TypeVar("T")

class A(Generic[R]):
    var = B[R]()  # E: "R" is a type variable and only valid in type context

class B(Generic[T]): ...

Expected Behavior

Either:

  1. no errors, or
  2. mypy doesn't support forward references in value contexts for stub files, and this emits a used-before-def error at B[R]().

Your Environment

  • Mypy version used: 1.17
  • Python version used: 3.11, 3.12

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