Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,13 +639,16 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ
t,
code=codes.VALID_TYPE,
)
else:
if not self.allow_final:
self.fail(
"Final can be only used as an outermost qualifier in a variable annotation",
t,
code=codes.VALID_TYPE,
)
elif not self.allow_final:
self.fail(
"Final can be only used as an outermost qualifier in a variable annotation",
t,
code=codes.VALID_TYPE,
)
elif t.args:
# Nested Final[...] is accepted here (e.g. ClassVar[Final[...]] on 3.13+);
# preserve and return the inner type instead of collapsing to Any.
return self.anal_type(t.args[0])
return AnyType(TypeOfAny.from_error)
elif fullname in TUPLE_NAMES:
# Tuple is special because it is involved in builtin import cycle
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-final.test
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,18 @@ class A:
b: ClassVar[Final[int]] = 1
c: ClassVar[Final] = 1

[case testFinalUsedWithClassVarAfterPy313PreservesType]
# flags: --python-version 3.13
# Nested Final inside ClassVar should preserve the inner type (#21906).
from typing import ClassVar, Final, reveal_type

class B: pass

class A:
cv: ClassVar[Final[dict[type[B], A]] = {}

reveal_type(A.cv) # N: Revealed type is "builtins.dict[type[B], __main__.A"

[case testFinalClassWithAbstractMethod]
from typing import final
from abc import ABC, abstractmethod
Expand Down
Loading