|
| 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 | +`mod.py`: |
| 9 | + |
| 10 | +```py |
| 11 | +from typing import Final, Annotated |
| 12 | + |
| 13 | +FINAL_A: int = 1 |
| 14 | +FINAL_B: Annotated[Final[int], "the annotation for FINAL_B"] = 1 |
| 15 | +FINAL_C: Final[Annotated[int, "the annotation for FINAL_C"]] = 1 |
| 16 | +FINAL_D: Final = 1 |
| 17 | +FINAL_E: "Final[int]" = 1 |
| 18 | + |
| 19 | +reveal_type(FINAL_A) # revealed: Literal[1] |
| 20 | +reveal_type(FINAL_B) # revealed: Literal[1] |
| 21 | +reveal_type(FINAL_C) # revealed: Literal[1] |
| 22 | +reveal_type(FINAL_D) # revealed: Literal[1] |
| 23 | +reveal_type(FINAL_E) # revealed: Literal[1] |
| 24 | + |
| 25 | +# TODO: All of these should be errors: |
| 26 | +FINAL_A = 2 |
| 27 | +FINAL_B = 2 |
| 28 | +FINAL_C = 2 |
| 29 | +FINAL_D = 2 |
| 30 | +FINAL_E = 2 |
| 31 | +``` |
| 32 | + |
| 33 | +Public types: |
| 34 | + |
| 35 | +```py |
| 36 | +from mod import FINAL_A, FINAL_B, FINAL_C, FINAL_D, FINAL_E |
| 37 | + |
| 38 | +# TODO: All of these should be Literal[1] |
| 39 | +reveal_type(FINAL_A) # revealed: int |
| 40 | +reveal_type(FINAL_B) # revealed: int |
| 41 | +reveal_type(FINAL_C) # revealed: int |
| 42 | +reveal_type(FINAL_D) # revealed: Unknown |
| 43 | +reveal_type(FINAL_E) # revealed: int |
| 44 | +``` |
| 45 | + |
| 46 | +## Too many arguments |
| 47 | + |
| 48 | +```py |
| 49 | +from typing import Final |
| 50 | + |
| 51 | +class C: |
| 52 | + # error: [invalid-type-form] "Type qualifier `typing.Final` expects exactly one type parameter" |
| 53 | + x: Final[int, str] = 1 |
| 54 | +``` |
| 55 | + |
| 56 | +## Illegal `Final` in type expression |
| 57 | + |
| 58 | +```py |
| 59 | +from typing import Final |
| 60 | + |
| 61 | +class C: |
| 62 | + # error: [invalid-type-form] "Type qualifier `typing.Final` is not allowed in type expressions (only in annotation expressions)" |
| 63 | + x: Final | int |
| 64 | + |
| 65 | + # error: [invalid-type-form] "Type qualifier `typing.Final` is not allowed in type expressions (only in annotation expressions)" |
| 66 | + y: int | Final[str] |
| 67 | +``` |
| 68 | + |
| 69 | +## No assignment |
| 70 | + |
| 71 | +```py |
| 72 | +from typing import Final |
| 73 | + |
| 74 | +DECLARED_THEN_BOUND: Final[int] |
| 75 | +DECLARED_THEN_BOUND = 1 |
| 76 | +``` |
| 77 | + |
| 78 | +## No assignment for bare `Final` |
| 79 | + |
| 80 | +```py |
| 81 | +from typing import Final |
| 82 | + |
| 83 | +# TODO: This should be an error |
| 84 | +NO_RHS: Final |
| 85 | +``` |
| 86 | + |
| 87 | +[`typing.final`]: https://docs.python.org/3/library/typing.html#typing.Final |
0 commit comments