Skip to content

Commit 8f1c56e

Browse files
committed
[red-knot] Preliminary tests for typing.Final
1 parent 102c2ee commit 8f1c56e

File tree

1 file changed

+85
-0
lines changed
  • crates/red_knot_python_semantic/resources/mdtest/type_qualifiers

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# `typing.Final`
2+
3+
[`typing.Final`] is a type qualifier that is used to indicate that a symbol may not be reassigned in
4+
any scope. Final names declared in class scopes cannot be overridden in subclasses.
5+
6+
## Basic
7+
8+
```py path=mod.py
9+
from typing import Final, Annotated
10+
11+
FINAL_A: int = 1
12+
FINAL_B: Annotated[Final[int], "the annotation for FINAL_B"] = 1
13+
FINAL_C: Final[Annotated[int, "the annotation for FINAL_C"]] = 1
14+
FINAL_D: Final = 1
15+
FINAL_E: "Final[int]" = 1
16+
17+
reveal_type(FINAL_A) # revealed: Literal[1]
18+
reveal_type(FINAL_B) # revealed: Literal[1]
19+
reveal_type(FINAL_C) # revealed: Literal[1]
20+
reveal_type(FINAL_D) # revealed: Literal[1]
21+
reveal_type(FINAL_E) # revealed: Literal[1]
22+
23+
# TODO: All of these should be errors:
24+
FINAL_A = 2
25+
FINAL_B = 2
26+
FINAL_C = 2
27+
FINAL_D = 2
28+
FINAL_E = 2
29+
```
30+
31+
Public types:
32+
33+
```py
34+
from mod import FINAL_A, FINAL_B, FINAL_C, FINAL_D, FINAL_E
35+
36+
# TODO: All of these should be Literal[1]
37+
reveal_type(FINAL_A) # revealed: int
38+
reveal_type(FINAL_B) # revealed: int
39+
reveal_type(FINAL_C) # revealed: int
40+
reveal_type(FINAL_D) # revealed: Unknown
41+
reveal_type(FINAL_E) # revealed: int
42+
```
43+
44+
## Too many arguments
45+
46+
```py
47+
from typing import Final
48+
49+
class C:
50+
# error: [invalid-type-form] "Type qualifier `typing.Final` expects exactly one type parameter"
51+
x: Final[int, str] = 1
52+
```
53+
54+
## Illegal `Final` in type expression
55+
56+
```py
57+
from typing import Final
58+
59+
class C:
60+
# error: [invalid-type-form] "Type qualifier `typing.Final` is not allowed in type expressions (only in annotation expressions)"
61+
x: Final | int
62+
63+
# error: [invalid-type-form] "Type qualifier `typing.Final` is not allowed in type expressions (only in annotation expressions)"
64+
y: int | Final[str]
65+
```
66+
67+
## No assignment
68+
69+
```py
70+
from typing import Final
71+
72+
DECLARED_THEN_BOUND: Final[int]
73+
DECLARED_THEN_BOUND = 1
74+
```
75+
76+
## No assignment for bare `Final`
77+
78+
```py
79+
from typing import Final
80+
81+
# TODO: This should be an error
82+
NO_RHS: Final
83+
```
84+
85+
[`typing.final`]: https://docs.python.org/3/library/typing.html#typing.Final

0 commit comments

Comments
 (0)