Debian Codegraph @

docs/source/literal_types.rst

raw
1 Literal types and Enums
2 =======================
3
4 .. _literal_types:
5
6 Literal types
7 -------------
8
9 Literal types let you indicate that an expression is equal to some specific
10 primitive value. For example, if we annotate a variable with type ``Literal["foo"]``,
11 mypy will understand that variable is not only of type ``str``, but is also
12 equal to specifically the string ``"foo"``.
13
14 This feature is primarily useful when annotating functions that behave
15 differently based on the exact value the caller provides. For example,
16 suppose we have a function ``fetch_data(...)`` that returns ``bytes`` if the
17 first argument is ``True``, and ``str`` if it's ``False``. We can construct a
18 precise type signature for this function using ``Literal[...]`` and overloads:
19
20 .. code-block:: python
21
22 from typing import overload, Union, Literal
23
24 # The first two overloads use Literal[...] so we can
25 # have precise return types:
26
27 @overload
28 def fetch_data(raw: Literal[True]) -> bytes: ...
29 @overload
30 def fetch_data(raw: Literal[False]) -> str: ...
31
32 # The last overload is a fallback in case the caller
33 # provides a regular bool:
34
35 @overload
36 def fetch_data(raw: bool) -> Union[bytes, str]: ...
37
38 def fetch_data(raw: bool) -> Union[bytes, str]:
39 # Implementation is omitted
40 ...
41
42 reveal_type(fetch_data(True)) # Revealed type is "bytes"
43 reveal_type(fetch_data(False)) # Revealed type is "str"
44
45 # Variables declared without annotations will continue to have an
46 # inferred type of 'bool'.
47
48 variable = True
49 reveal_type(fetch_data(variable)) # Revealed type is "Union[bytes, str]"
50
51 .. note::
52
53 The examples in this page import ``Literal`` as well as ``Final`` and
54 ``TypedDict`` from the ``typing`` module. These types were added to
55 ``typing`` in Python 3.8, but are also available for use in Python
56 3.4 - 3.7 via the ``typing_extensions`` package.
57
58 Parameterizing Literals
59 ***********************
60
61 Literal types may contain one or more literal bools, ints, strs, bytes, and
62 enum values. However, literal types **cannot** contain arbitrary expressions:
63 types like ``Literal[my_string.trim()]``, ``Literal[x > 3]``, or ``Literal[3j + 4]``
64 are all illegal.
65
66 Literals containing two or more values are equivalent to the union of those values.
67 So, ``Literal[-3, b"foo", MyEnum.A]`` is equivalent to
68 ``Union[Literal[-3], Literal[b"foo"], Literal[MyEnum.A]]``. This makes writing more
69 complex types involving literals a little more convenient.
70
71 Literal types may also contain ``None``. Mypy will treat ``Literal[None]`` as being
72 equivalent to just ``None``. This means that ``Literal[4, None]``,
73 ``Literal[4] | None``, and ``Optional[Literal[4]]`` are all equivalent.
74
75 Literals may also contain aliases to other literal types. For example, the
76 following program is legal:
77
78 .. code-block:: python
79
80 PrimaryColors = Literal["red", "blue", "yellow"]
81 SecondaryColors = Literal["purple", "green", "orange"]
82 AllowedColors = Literal[PrimaryColors, SecondaryColors]
83
84 def paint(color: AllowedColors) -> None: ...
85
86 paint("red") # Type checks!
87 paint("turquoise") # Does not type check
88
89 Literals may not contain any other kind of type or expression. This means doing
90 ``Literal[my_instance]``, ``Literal[Any]``, ``Literal[3.14]``, or
91 ``Literal[{"foo": 2, "bar": 5}]`` are all illegal.
92
93 Declaring literal variables
94 ***************************
95
96 You must explicitly add an annotation to a variable to declare that it has
97 a literal type:
98
99 .. code-block:: python
100
101 a: Literal[19] = 19
102 reveal_type(a) # Revealed type is "Literal[19]"
103
104 In order to preserve backwards-compatibility, variables without this annotation
105 are **not** assumed to be literals:
106
107 .. code-block:: python
108
109 b = 19
110 reveal_type(b) # Revealed type is "int"
111
112 If you find repeating the value of the variable in the type hint to be tedious,
113 you can instead change the variable to be ``Final`` (see :ref:`final_attrs`):
114
115 .. code-block:: python
116
117 from typing import Final, Literal
118
119 def expects_literal(x: Literal[19]) -> None: pass
120
121 c: Final = 19
122
123 reveal_type(c) # Revealed type is "Literal[19]?"
124 expects_literal(c) # ...and this type checks!
125
126 If you do not provide an explicit type in the ``Final``, the type of ``c`` becomes
127 *context-sensitive*: mypy will basically try "substituting" the original assigned
128 value whenever it's used before performing type checking. This is why the revealed
129 type of ``c`` is ``Literal[19]?``: the question mark at the end reflects this
130 context-sensitive nature.
131
132 For example, mypy will type check the above program almost as if it were written like so:
133
134 .. code-block:: python
135
136 from typing import Final, Literal
137
138 def expects_literal(x: Literal[19]) -> None: pass
139
140 reveal_type(19)
141 expects_literal(19)
142
143 This means that while changing a variable to be ``Final`` is not quite the same thing
144 as adding an explicit ``Literal[...]`` annotation, it often leads to the same effect
145 in practice.
146
147 The main cases where the behavior of context-sensitive vs true literal types differ are
148 when you try using those types in places that are not explicitly expecting a ``Literal[...]``.
149 For example, compare and contrast what happens when you try appending these types to a list:
150
151 .. code-block:: python
152
153 from typing import Final, Literal
154
155 a: Final = 19
156 b: Literal[19] = 19
157
158 # Mypy will choose to infer list[int] here.
159 list_of_ints = []
160 list_of_ints.append(a)
161 reveal_type(list_of_ints) # Revealed type is "list[int]"
162
163 # But if the variable you're appending is an explicit Literal, mypy
164 # will infer list[Literal[19]].
165 list_of_lits = []
166 list_of_lits.append(b)
167 reveal_type(list_of_lits) # Revealed type is "list[Literal[19]]"
168
169
170 Intelligent indexing
171 ********************
172
173 We can use Literal types to more precisely index into structured heterogeneous
174 types such as tuples, NamedTuples, and TypedDicts. This feature is known as
175 *intelligent indexing*.
176
177 For example, when we index into a tuple using some int, the inferred type is
178 normally the union of the tuple item types. However, if we want just the type
179 corresponding to some particular index, we can use Literal types like so:
180
181 .. code-block:: python
182
183 from typing import TypedDict
184
185 tup = ("foo", 3.4)
186
187 # Indexing with an int literal gives us the exact type for that index
188 reveal_type(tup[0]) # Revealed type is "str"
189
190 # But what if we want the index to be a variable? Normally mypy won't
191 # know exactly what the index is and so will return a less precise type:
192 int_index = 0
193 reveal_type(tup[int_index]) # Revealed type is "Union[str, float]"
194
195 # But if we use either Literal types or a Final int, we can gain back
196 # the precision we originally had:
197 lit_index: Literal[0] = 0
198 fin_index: Final = 0
199 reveal_type(tup[lit_index]) # Revealed type is "str"
200 reveal_type(tup[fin_index]) # Revealed type is "str"
201
202 # We can do the same thing with with TypedDict and str keys:
203 class MyDict(TypedDict):
204 name: str
205 main_id: int
206 backup_id: int
207
208 d: MyDict = {"name": "Saanvi", "main_id": 111, "backup_id": 222}
209 name_key: Final = "name"
210 reveal_type(d[name_key]) # Revealed type is "str"
211
212 # You can also index using unions of literals
213 id_key: Literal["main_id", "backup_id"]
214 reveal_type(d[id_key]) # Revealed type is "int"
215
216 .. _tagged_unions:
217
218 Tagged unions
219 *************
220
221 When you have a union of types, you can normally discriminate between each type
222 in the union by using ``isinstance`` checks. For example, if you had a variable ``x`` of
223 type ``Union[int, str]``, you could write some code that runs only if ``x`` is an int
224 by doing ``if isinstance(x, int): ...``.
225
226 However, it is not always possible or convenient to do this. For example, it is not
227 possible to use ``isinstance`` to distinguish between two different TypedDicts since
228 at runtime, your variable will simply be just a dict.
229
230 Instead, what you can do is *label* or *tag* your TypedDicts with a distinct Literal
231 type. Then, you can discriminate between each kind of TypedDict by checking the label:
232
233 .. code-block:: python
234
235 from typing import Literal, TypedDict, Union
236
237 class NewJobEvent(TypedDict):
238 tag: Literal["new-job"]
239 job_name: str
240 config_file_path: str
241
242 class CancelJobEvent(TypedDict):
243 tag: Literal["cancel-job"]
244 job_id: int
245
246 Event = Union[NewJobEvent, CancelJobEvent]
247
248 def process_event(event: Event) -> None:
249 # Since we made sure both TypedDicts have a key named 'tag', it's
250 # safe to do 'event["tag"]'. This expression normally has the type
251 # Literal["new-job", "cancel-job"], but the check below will narrow
252 # the type to either Literal["new-job"] or Literal["cancel-job"].
253 #
254 # This in turns narrows the type of 'event' to either NewJobEvent
255 # or CancelJobEvent.
256 if event["tag"] == "new-job":
257 print(event["job_name"])
258 else:
259 print(event["job_id"])
260
261 While this feature is mostly useful when working with TypedDicts, you can also
262 use the same technique with regular objects, tuples, or namedtuples.
263
264 Similarly, tags do not need to be specifically str Literals: they can be any type
265 you can normally narrow within ``if`` statements and the like. For example, you
266 could have your tags be int or Enum Literals or even regular classes you narrow
267 using ``isinstance()`` (Python 3.12 syntax):
268
269 .. code-block:: python
270
271 class Wrapper[T]:
272 def __init__(self, inner: T) -> None:
273 self.inner = inner
274
275 def process(w: Wrapper[int] | Wrapper[str]) -> None:
276 # Doing `if isinstance(w, Wrapper[int])` does not work: isinstance requires
277 # that the second argument always be an *erased* type, with no generics.
278 # This is because generics are a typing-only concept and do not exist at
279 # runtime in a way `isinstance` can always check.
280 #
281 # However, we can side-step this by checking the type of `w.inner` to
282 # narrow `w` itself:
283 if isinstance(w.inner, int):
284 reveal_type(w) # Revealed type is "Wrapper[int]"
285 else:
286 reveal_type(w) # Revealed type is "Wrapper[str]"
287
288 This feature is sometimes called "sum types" or "discriminated union types"
289 in other programming languages.
290
291 Exhaustiveness checking
292 ***********************
293
294 You may want to check that some code covers all possible
295 ``Literal`` or ``Enum`` cases. Example:
296
297 .. code-block:: python
298
299 from typing import Literal
300
301 PossibleValues = Literal['one', 'two']
302
303 def validate(x: PossibleValues) -> bool:
304 if x == 'one':
305 return True
306 elif x == 'two':
307 return False
308 raise ValueError(f'Invalid value: {x}')
309
310 assert validate('one') is True
311 assert validate('two') is False
312
313 In the code above, it's easy to make a mistake. You can
314 add a new literal value to ``PossibleValues`` but forget
315 to handle it in the ``validate`` function:
316
317 .. code-block:: python
318
319 PossibleValues = Literal['one', 'two', 'three']
320
321 Mypy won't catch that ``'three'`` is not covered. If you want mypy to
322 perform an exhaustiveness check, you need to update your code to use an
323 ``assert_never()`` check:
324
325 .. code-block:: python
326
327 from typing import Literal, NoReturn
328 from typing_extensions import assert_never
329
330 PossibleValues = Literal['one', 'two']
331
332 def validate(x: PossibleValues) -> bool:
333 if x == 'one':
334 return True
335 elif x == 'two':
336 return False
337 assert_never(x)
338
339 Now if you add a new value to ``PossibleValues`` but don't update ``validate``,
340 mypy will spot the error:
341
342 .. code-block:: python
343
344 PossibleValues = Literal['one', 'two', 'three']
345
346 def validate(x: PossibleValues) -> bool:
347 if x == 'one':
348 return True
349 elif x == 'two':
350 return False
351 # Error: Argument 1 to "assert_never" has incompatible type "Literal['three']";
352 # expected "NoReturn"
353 assert_never(x)
354
355 If runtime checking against unexpected values is not needed, you can
356 leave out the ``assert_never`` call in the above example, and mypy
357 will still generate an error about function ``validate`` returning
358 without a value:
359
360 .. code-block:: python
361
362 PossibleValues = Literal['one', 'two', 'three']
363
364 # Error: Missing return statement
365 def validate(x: PossibleValues) -> bool:
366 if x == 'one':
367 return True
368 elif x == 'two':
369 return False
370
371 Exhaustiveness checking is also supported for match statements (Python 3.10 and later):
372
373 .. code-block:: python
374
375 def validate(x: PossibleValues) -> bool:
376 match x:
377 case 'one':
378 return True
379 case 'two':
380 return False
381 assert_never(x)
382
383
384 Limitations
385 ***********
386
387 Mypy will not understand expressions that use variables of type ``Literal[..]``
388 on a deep level. For example, if you have a variable ``a`` of type ``Literal[3]``
389 and another variable ``b`` of type ``Literal[5]``, mypy will infer that
390 ``a + b`` has type ``int``, **not** type ``Literal[8]``.
391
392 The basic rule is that literal types are treated as just regular subtypes of
393 whatever type the parameter has. For example, ``Literal[3]`` is treated as a
394 subtype of ``int`` and so will inherit all of ``int``'s methods directly. This
395 means that ``Literal[3].__add__`` accepts the same arguments and has the same
396 return type as ``int.__add__``.
397
398
399 Enums
400 -----
401
402 Mypy has special support for :py:class:`enum.Enum` and its subclasses:
403 :py:class:`enum.IntEnum`, :py:class:`enum.Flag`, :py:class:`enum.IntFlag`,
404 and :py:class:`enum.StrEnum`.
405
406 .. code-block:: python
407
408 from enum import Enum
409
410 class Direction(Enum):
411 up = 'up'
412 down = 'down'
413
414 reveal_type(Direction.up) # Revealed type is "Literal[Direction.up]?"
415 reveal_type(Direction.down) # Revealed type is "Literal[Direction.down]?"
416
417 You can use enums to annotate types as you would expect:
418
419 .. code-block:: python
420
421 class Movement:
422 def __init__(self, direction: Direction, speed: float) -> None:
423 self.direction = direction
424 self.speed = speed
425
426 Movement(Direction.up, 5.0) # ok
427 Movement('up', 5.0) # E: Argument 1 to "Movement" has incompatible type "str"; expected "Direction"
428
429 Exhaustiveness checking
430 ***********************
431
432 Similar to ``Literal`` types, ``Enum`` supports exhaustiveness checking.
433 Let's start with a definition:
434
435 .. code-block:: python
436
437 from enum import Enum
438 from typing import NoReturn
439 from typing_extensions import assert_never
440
441 class Direction(Enum):
442 up = 'up'
443 down = 'down'
444
445 Now, let's use an exhaustiveness check:
446
447 .. code-block:: python
448
449 def choose_direction(direction: Direction) -> None:
450 if direction is Direction.up:
451 reveal_type(direction) # N: Revealed type is "Literal[Direction.up]"
452 print('Going up!')
453 return
454 elif direction is Direction.down:
455 print('Down')
456 return
457 # This line is never reached
458 assert_never(direction)
459
460 If we forget to handle one of the cases, mypy will generate an error:
461
462 .. code-block:: python
463
464 def choose_direction(direction: Direction) -> None:
465 if direction == Direction.up:
466 print('Going up!')
467 return
468 assert_never(direction) # E: Argument 1 to "assert_never" has incompatible type "Direction"; expected "NoReturn"
469
470 Exhaustiveness checking is also supported for match statements (Python 3.10 and later).
471 For match statements specifically, inexhaustive matches can be caught
472 without needing to use ``assert_never`` by using
473 :option:`--enable-error-code exhaustive-match <mypy --enable-error-code>`.
474
475
476 Extra Enum checks
477 *****************
478
479 Mypy also tries to support special features of ``Enum``
480 the same way Python's runtime does:
481
482 - Any ``Enum`` class with values is implicitly :ref:`final <final_attrs>`.
483 This is what happens in CPython:
484
485 .. code-block:: python
486
487 >>> class AllDirection(Direction):
488 ... left = 'left'
489 ... right = 'right'
490 Traceback (most recent call last):
491 ...
492 TypeError: AllDirection: cannot extend enumeration 'Direction'
493
494 Mypy also catches this error:
495
496 .. code-block:: python
497
498 class AllDirection(Direction): # E: Cannot inherit from final class "Direction"
499 left = 'left'
500 right = 'right'
501
502 - All ``Enum`` fields are implicitly ``final`` as well.
503
504 .. code-block:: python
505
506 Direction.up = '^' # E: Cannot assign to final attribute "up"
507
508 - All field names are checked to be unique.
509
510 .. code-block:: python
511
512 class Some(Enum):
513 x = 1
514 x = 2 # E: Attempted to reuse member name "x" in Enum definition "Some"
515
516 - Base classes have no conflicts and mixin types are correct.
517
518 .. code-block:: python
519
520 class WrongEnum(str, int, enum.Enum):
521 # E: Only a single data type mixin is allowed for Enum subtypes, found extra "int"
522 ...
523
524 class MixinAfterEnum(enum.Enum, Mixin): # E: No base classes are allowed after "enum.Enum"
525 ...