python / python/mypy

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

Open
#19,601 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the stub.pyi reproducer and inspect how mypy handles forward references in value expressions in stub files. Compare the current diagnostic with the two expected outcomes described in the issue; done means the behavior is either accepted or reported as used-before-def at B[R]().

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.