← Back to index

literals_semantics.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 4
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the semantics of the Literal special form.
3"""
4
5from typing import Literal
6from typing import Literal as L
7
8
9v1: Literal[3] = 3
10v2: Literal[3] = 4 # E
[invalid-assignment] Object of type `Literal[4]` is not assignable to `Literal[3]`
12v3: L[-3] = -3
15# > Literal[20] and Literal[0x14] are equivalent
16def func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):
17 x1: Literal[0x14] = a
18 x2: Literal[0x14] = b
19 x3: Literal[0x14] = c
22# > Literal[0] and Literal[False] are not equivalent
23def func2(a: Literal[0], b: Literal[False]):
24 x1: Literal[False] = a # E
[invalid-assignment] Object of type `Literal[0]` is not assignable to `Literal[False]`
25 x2: Literal[0] = b # E
[invalid-assignment] Object of type `Literal[False]` is not assignable to `Literal[0]`
28# > Given some value v that is a member of type T, the type Literal[v] shall
29# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.
30def func3(a: L[3, 4, 5]):
31 b = a.__add__(3)
32 c = a + 3
33 a += 3 # E
[invalid-assignment] Object of type `Literal[6, 7, 8]` is not assignable to `Literal[3, 4, 5]`
36# > When a Literal is parameterized with more than one value, it’s treated
37# > as exactly equivalent to the union of those types.
38def func4(a: L[None, 3] | L[3, "foo", b"bar", True]):
39 x1: Literal[3, b"bar", True, "foo", None] = a
40 a = x1