python / python/mypy

Allow Annotated to wrap Final and ClassVar

Open
#12,061 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

The behavior of Annotated has been changed so that it is allowed at runtime to wrap ClassVar and Final. This change helps avoid friction with other users of annotations; see https://bugs.python.org/issue46491 for context. This change has landed in 3.11 and has been backported to 3.9, 3.10, and typing_extensions. mypy should follow suit in allowing the wrapping in order to allow the friction lifting to happen in practice.

To Reproduce

from typing import Annotated, ClassVar, Final

class C:
    classvar: Annotated[ClassVar[int], (2, 5)] = 4
    const: Annotated[Final[int], "metadata"] = 4

Expected Behavior

The above code should type check.

Actual Behavior

antest/antest.py:4: error: Invalid type: ClassVar nested inside other type
antest/antest.py:5: error: Final can be only used as an outermost qualifier in a variable annotation
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.931
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.9.9
  • Operating system and version: Gentoo Linux stable

Additional Context
Corresponding issue for dataclasses (incl InitVar) is at https://bugs.python.org/issue46511
pyright changed at https://github.com/microsoft/pyright/commit/8ce7fa6e0ad883fb17407add955273bbfbe506c5
pytype issue at https://github.com/google/pytype/issues/1110
pyre issue at https://github.com/facebook/pyre-check/issues/577

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 by running the issue's Annotated, ClassVar, and Final reproducer against the current checker and trace the existing handling of these annotation forms. Add regression coverage showing both examples type check without errors; the work is done when the tests pass and the reported diagnostics are gone.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.