Skip to content

fix(type-analysis): preserve nested Final types in ClassVar - #21909

Open
daleselaji-dev wants to merge 1 commit into
python:masterfrom
daleselaji-dev:codex/fix-21906
Open

fix(type-analysis): preserve nested Final types in ClassVar#21909
daleselaji-dev wants to merge 1 commit into
python:masterfrom
daleselaji-dev:codex/fix-21906

Conversation

@daleselaji-dev

Copy link
Copy Markdown

Problem

On Python 3.13 and newer, ClassVar[Final[T]] is accepted but the annotated class variable resolves to Any instead of preserving T.

Root Cause

The type analyzer allows nested Final while analyzing ClassVar, but the Final[...] special-form branch still returns an error AnyType after accepting the nested form. This silently discards the inner type.

Solution

When nested Final[...] is allowed and has a type argument, analyze and return that inner type. The existing diagnostic remains unchanged for contexts where nested Final is not permitted.

Changes

  • Preserve the inner type for accepted nested Final[...] annotations.
  • Add a Python 3.13 regression case asserting that ClassVar[Final[dict[str, int]]] reveals the dictionary type.

Testing

  • Baseline on current master (b974556f): the issue reproducer revealed Any under --python-version 3.13.
  • py -3.10 -m pytest 'mypy/test/testcheck.py::TypeCheckSuite::check-final.test' -q: 82 passed.
  • py -3.10 -m black --check mypy/typeanal.py: passed.
  • py -3.10 -m ruff check mypy/typeanal.py: passed.
  • py -3.10 -m compileall -q mypy/typeanal.py: passed.
  • py -3.10 -m mypy --config-file mypy_self_check.ini -p mypy: 196 source files.
  • git diff --check: passed.
  • The full repository test suite was not run.

Compatibility/Risk

This changes only the result of an already-accepted nested Final[...] type form. Unsupported nested Final uses continue to report the existing validation error; no runtime behavior or public runtime API changes.

Notes for Reviewer

The regression test uses --python-version 3.13 while running the test harness on Python 3.10, so it exercises the version-gated type-analysis path without requiring a local Python 3.13 interpreter.

Linked Issue

Fixes #21906

@daleselaji-dev
daleselaji-dev marked this pull request as ready for review August 29, 2026 03:02
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mypy treating type of final class variable in dataclass as Any

1 participant