Debian Codegraph @

Doc/reference/compound_stmts.rst

raw
1 .. _compound:
2
3 *******************
4 Compound statements
5 *******************
6
7 .. index:: pair: compound; statement
8
9 Compound statements contain (groups of) other statements; they affect or control
10 the execution of those other statements in some way. In general, compound
11 statements span multiple lines, although in simple incarnations a whole compound
12 statement may be contained in one line.
13
14 The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement
15 traditional control flow constructs. :keyword:`try` specifies exception
16 handlers and/or cleanup code for a group of statements, while the
17 :keyword:`with` statement allows the execution of initialization and
18 finalization code around a block of code. Function and class definitions are
19 also syntactically compound statements.
20
21 .. index::
22 single: clause
23 single: suite
24 single: ; (semicolon)
25
26 A compound statement consists of one or more 'clauses.' A clause consists of a
27 header and a 'suite.' The clause headers of a particular compound statement are
28 all at the same indentation level. Each clause header begins with a uniquely
29 identifying keyword and ends with a colon. A suite is a group of statements
30 controlled by a clause. A suite can be one or more semicolon-separated simple
31 statements on the same line as the header, following the header's colon, or it
32 can be one or more indented statements on subsequent lines. Only the latter
33 form of a suite can contain nested compound statements; the following is illegal,
34 mostly because it wouldn't be clear to which :keyword:`if` clause a following
35 :keyword:`else` clause would belong::
36
37 if test1: if test2: print(x)
38
39 Also note that the semicolon binds tighter than the colon in this context, so
40 that in the following example, either all or none of the :func:`print` calls are
41 executed::
42
43 if x < y < z: print(x); print(y); print(z)
44
45 Summarizing:
46
47
48 .. productionlist:: python-grammar
49 compound_stmt: `if_stmt`
50 : | `while_stmt`
51 : | `for_stmt`
52 : | `try_stmt`
53 : | `with_stmt`
54 : | `match_stmt`
55 : | `funcdef`
56 : | `classdef`
57 : | `async_with_stmt`
58 : | `async_for_stmt`
59 : | `async_funcdef`
60 suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT
61 statement: `stmt_list` NEWLINE | `compound_stmt`
62 stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"]
63
64 .. index::
65 single: NEWLINE token
66 single: DEDENT token
67 pair: dangling; else
68
69 Note that statements always end in a ``NEWLINE`` possibly followed by a
70 ``DEDENT``. Also note that optional continuation clauses always begin with a
71 keyword that cannot start a statement, thus there are no ambiguities (the
72 'dangling :keyword:`else`' problem is solved in Python by requiring nested
73 :keyword:`if` statements to be indented).
74
75 The formatting of the grammar rules in the following sections places each clause
76 on a separate line for clarity.
77
78
79 .. _if:
80 .. _elif:
81 .. _else:
82
83 The :keyword:`!if` statement
84 ============================
85
86 .. index::
87 ! pair: statement; if
88 pair: keyword; elif
89 pair: keyword; else
90 single: : (colon); compound statement
91
92 The :keyword:`if` statement is used for conditional execution:
93
94 .. productionlist:: python-grammar
95 if_stmt: "if" `assignment_expression` ":" `suite`
96 : ("elif" `assignment_expression` ":" `suite`)*
97 : ["else" ":" `suite`]
98
99 It selects exactly one of the suites by evaluating the expressions one by one
100 until one is found to be true (see section :ref:`booleans` for the definition of
101 true and false); then that suite is executed (and no other part of the
102 :keyword:`if` statement is executed or evaluated). If all expressions are
103 false, the suite of the :keyword:`else` clause, if present, is executed.
104
105
106 .. _while:
107
108 The :keyword:`!while` statement
109 ===============================
110
111 .. index::
112 ! pair: statement; while
113 pair: keyword; else
114 pair: loop; statement
115 single: : (colon); compound statement
116
117 The :keyword:`while` statement is used for repeated execution as long as an
118 expression is true:
119
120 .. productionlist:: python-grammar
121 while_stmt: "while" `assignment_expression` ":" `suite`
122 : ["else" ":" `suite`]
123
124 This repeatedly tests the expression and, if it is true, executes the first
125 suite; if the expression is false (which may be the first time it is tested) the
126 suite of the :keyword:`!else` clause, if present, is executed and the loop
127 terminates.
128
129 .. index::
130 pair: statement; break
131 pair: statement; continue
132
133 A :keyword:`break` statement executed in the first suite terminates the loop
134 without executing the :keyword:`!else` clause's suite. A :keyword:`continue`
135 statement executed in the first suite skips the rest of the suite and goes back
136 to testing the expression.
137
138
139 .. _for:
140
141 The :keyword:`!for` statement
142 =============================
143
144 .. index::
145 ! pair: statement; for
146 pair: keyword; in
147 pair: keyword; else
148 pair: target; list
149 pair: loop; statement
150 pair: object; sequence
151 single: : (colon); compound statement
152
153 The :keyword:`for` statement is used to iterate over the elements of a sequence
154 (such as a string, tuple or list) or other iterable object:
155
156 .. productionlist:: python-grammar
157 for_stmt: "for" `target_list` "in" `starred_list` ":" `suite`
158 : ["else" ":" `suite`]
159
160 The ``starred_list`` expression is evaluated once; it should yield an
161 :term:`iterable` object. An :term:`iterator` is created for that iterable.
162 The first item provided
163 by the iterator is then assigned to the target list using the standard
164 rules for assignments (see :ref:`assignment`), and the suite is executed. This
165 repeats for each item provided by the iterator. When the iterator is exhausted,
166 the suite in the :keyword:`!else` clause,
167 if present, is executed, and the loop terminates.
168
169 .. index::
170 pair: statement; break
171 pair: statement; continue
172
173 A :keyword:`break` statement executed in the first suite terminates the loop
174 without executing the :keyword:`!else` clause's suite. A :keyword:`continue`
175 statement executed in the first suite skips the rest of the suite and continues
176 with the next item, or with the :keyword:`!else` clause if there is no next
177 item.
178
179 The for-loop makes assignments to the variables in the target list.
180 This overwrites all previous assignments to those variables including
181 those made in the suite of the for-loop::
182
183 for i in range(10):
184 print(i)
185 i = 5 # this will not affect the for-loop
186 # because i will be overwritten with the next
187 # index in the range
188
189
190 .. index::
191 pair: built-in function; range
192
193 Names in the target list are not deleted when the loop is finished, but if the
194 sequence is empty, they will not have been assigned to at all by the loop. Hint:
195 the built-in type :func:`range` represents immutable arithmetic sequences of integers.
196 For instance, iterating ``range(3)`` successively yields 0, 1, and then 2.
197
198 .. versionchanged:: 3.11
199 Starred elements are now allowed in the expression list.
200
201
202 .. _try:
203
204 The :keyword:`!try` statement
205 =============================
206
207 .. index::
208 ! pair: statement; try
209 pair: keyword; except
210 pair: keyword; finally
211 pair: keyword; else
212 pair: keyword; as
213 single: : (colon); compound statement
214
215 The :keyword:`!try` statement specifies exception handlers and/or cleanup code
216 for a group of statements:
217
218 .. productionlist:: python-grammar
219 try_stmt: `try1_stmt` | `try2_stmt` | `try3_stmt`
220 try1_stmt: "try" ":" `suite`
221 : ("except" [`expression` ["as" `identifier`]] ":" `suite`)+
222 : ["else" ":" `suite`]
223 : ["finally" ":" `suite`]
224 try2_stmt: "try" ":" `suite`
225 : ("except" "*" `expression` ["as" `identifier`] ":" `suite`)+
226 : ["else" ":" `suite`]
227 : ["finally" ":" `suite`]
228 try3_stmt: "try" ":" `suite`
229 : "finally" ":" `suite`
230
231 Additional information on exceptions can be found in section :ref:`exceptions`,
232 and information on using the :keyword:`raise` statement to generate exceptions
233 may be found in section :ref:`raise`.
234
235
236 .. _except:
237
238 :keyword:`!except` clause
239 -------------------------
240
241 The :keyword:`!except` clause(s) specify one or more exception handlers. When no
242 exception occurs in the :keyword:`try` clause, no exception handler is executed.
243 When an exception occurs in the :keyword:`!try` suite, a search for an exception
244 handler is started. This search inspects the :keyword:`!except` clauses in turn
245 until one is found that matches the exception.
246 An expression-less :keyword:`!except` clause, if present, must be last;
247 it matches any exception.
248
249 For an :keyword:`!except` clause with an expression, the
250 expression must evaluate to an exception type or a tuple of exception types.
251 The raised exception matches an :keyword:`!except` clause whose expression evaluates
252 to the class or a :term:`non-virtual base class <abstract base class>` of the exception object,
253 or to a tuple that contains such a class.
254
255 If no :keyword:`!except` clause matches the exception,
256 the search for an exception handler
257 continues in the surrounding code and on the invocation stack. [#]_
258
259 If the evaluation of an expression
260 in the header of an :keyword:`!except` clause raises an exception,
261 the original search for a handler is canceled and a search starts for
262 the new exception in the surrounding code and on the call stack (it is treated
263 as if the entire :keyword:`try` statement raised the exception).
264
265 .. index:: single: as; except clause
266
267 When a matching :keyword:`!except` clause is found,
268 the exception is assigned to the target
269 specified after the :keyword:`!as` keyword in that :keyword:`!except` clause,
270 if present, and the :keyword:`!except` clause's suite is executed.
271 All :keyword:`!except` clauses must have an executable block.
272 When the end of this block is reached, execution continues
273 normally after the entire :keyword:`try` statement.
274 (This means that if two nested handlers exist for the same exception,
275 and the exception occurs in the :keyword:`!try` clause of the inner handler,
276 the outer handler will not handle the exception.)
277
278 When an exception has been assigned using ``as target``, it is cleared at the
279 end of the :keyword:`!except` clause. This is as if ::
280
281 except E as N:
282 foo
283
284 was translated to ::
285
286 except E as N:
287 try:
288 foo
289 finally:
290 del N
291
292 This means the exception must be assigned to a different name to be able to
293 refer to it after the :keyword:`!except` clause.
294 Exceptions are cleared because with the
295 traceback attached to them, they form a reference cycle with the stack frame,
296 keeping all locals in that frame alive until the next garbage collection occurs.
297
298 .. index::
299 pair: module; sys
300 pair: object; traceback
301
302 Before an :keyword:`!except` clause's suite is executed,
303 the exception is stored in the :mod:`sys` module, where it can be accessed
304 from within the body of the :keyword:`!except` clause by calling
305 :func:`sys.exception`. When leaving an exception handler, the exception
306 stored in the :mod:`sys` module is reset to its previous value::
307
308 >>> print(sys.exception())
309 None
310 >>> try:
311 ... raise TypeError
312 ... except:
313 ... print(repr(sys.exception()))
314 ... try:
315 ... raise ValueError
316 ... except:
317 ... print(repr(sys.exception()))
318 ... print(repr(sys.exception()))
319 ...
320 TypeError()
321 ValueError()
322 TypeError()
323 >>> print(sys.exception())
324 None
325
326
327 .. index::
328 pair: keyword; except_star
329
330 .. _except_star:
331
332 :keyword:`!except*` clause
333 --------------------------
334
335 The :keyword:`!except*` clause(s) specify one or more handlers for groups of
336 exceptions (:exc:`BaseExceptionGroup` instances). A :keyword:`try` statement
337 can have either :keyword:`except` or :keyword:`!except*` clauses, but not both.
338 The exception type for matching is mandatory in the case of :keyword:`!except*`,
339 so ``except*:`` is a syntax error. The type is interpreted as in the case of
340 :keyword:`!except`, but matching is performed on the exceptions contained in the
341 group that is being handled. An :exc:`TypeError` is raised if a matching
342 type is a subclass of :exc:`!BaseExceptionGroup`, because that would have
343 ambiguous semantics.
344
345 When an exception group is raised in the try block, each :keyword:`!except*`
346 clause splits (see :meth:`~BaseExceptionGroup.split`) it into the subgroups
347 of matching and non-matching exceptions. If the matching subgroup is not empty,
348 it becomes the handled exception (the value returned from :func:`sys.exception`)
349 and assigned to the target of the :keyword:`!except*` clause (if there is one).
350 Then, the body of the :keyword:`!except*` clause executes. If the non-matching
351 subgroup is not empty, it is processed by the next :keyword:`!except*` in the
352 same manner. This continues until all exceptions in the group have been matched,
353 or the last :keyword:`!except*` clause has run.
354
355 After all :keyword:`!except*` clauses execute, the group of unhandled exceptions
356 is merged with any exceptions that were raised or re-raised from within
357 :keyword:`!except*` clauses. This merged exception group propagates on.::
358
359 >>> try:
360 ... raise ExceptionGroup("eg",
361 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
362 ... except* TypeError as e:
363 ... print(f'caught {type(e)} with nested {e.exceptions}')
364 ... except* OSError as e:
365 ... print(f'caught {type(e)} with nested {e.exceptions}')
366 ...
367 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
368 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
369 + Exception Group Traceback (most recent call last):
370 | File "<doctest default[0]>", line 2, in <module>
371 | raise ExceptionGroup("eg",
372 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
373 | ExceptionGroup: eg (1 sub-exception)
374 +-+---------------- 1 ----------------
375 | ValueError: 1
376 +------------------------------------
377
378 If the exception raised from the :keyword:`try` block is not an exception group
379 and its type matches one of the :keyword:`!except*` clauses, it is caught and
380 wrapped by an exception group with an empty message string. This ensures that the
381 type of the target ``e`` is consistently :exc:`BaseExceptionGroup`::
382
383 >>> try:
384 ... raise BlockingIOError
385 ... except* BlockingIOError as e:
386 ... print(repr(e))
387 ...
388 ExceptionGroup('', (BlockingIOError(),))
389
390 :keyword:`break`, :keyword:`continue` and :keyword:`return`
391 cannot appear in an :keyword:`!except*` clause.
392
393
394 .. index::
395 pair: keyword; else
396 pair: statement; return
397 pair: statement; break
398 pair: statement; continue
399
400 .. _except_else:
401
402 :keyword:`!else` clause
403 -----------------------
404
405 The optional :keyword:`!else` clause is executed if the control flow leaves the
406 :keyword:`try` suite, no exception was raised, and no :keyword:`return`,
407 :keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in
408 the :keyword:`!else` clause are not handled by the preceding :keyword:`except`
409 clauses.
410
411
412 .. index:: pair: keyword; finally
413
414 .. _finally:
415
416 :keyword:`!finally` clause
417 --------------------------
418
419 If :keyword:`!finally` is present, it specifies a 'cleanup' handler. The
420 :keyword:`try` clause is executed, including any :keyword:`except`
421 and :keyword:`else <except_else>` clauses.
422 If an exception occurs in any of the clauses and is not handled,
423 the exception is temporarily saved.
424 The :keyword:`!finally` clause is executed. If there is a saved exception
425 it is re-raised at the end of the :keyword:`!finally` clause.
426 If the :keyword:`!finally` clause raises another exception, the saved exception
427 is set as the context of the new exception.
428 If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break`
429 or :keyword:`continue` statement, the saved exception is discarded::
430
431 >>> def f():
432 ... try:
433 ... 1/0
434 ... finally:
435 ... return 42
436 ...
437 >>> f()
438 42
439
440 The exception information is not available to the program during execution of
441 the :keyword:`!finally` clause.
442
443 .. index::
444 pair: statement; return
445 pair: statement; break
446 pair: statement; continue
447
448 When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is
449 executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally`
450 statement, the :keyword:`!finally` clause is also executed 'on the way out.'
451
452 The return value of a function is determined by the last :keyword:`return`
453 statement executed. Since the :keyword:`!finally` clause always executes, a
454 :keyword:`!return` statement executed in the :keyword:`!finally` clause will
455 always be the last one executed::
456
457 >>> def foo():
458 ... try:
459 ... return 'try'
460 ... finally:
461 ... return 'finally'
462 ...
463 >>> foo()
464 'finally'
465
466 .. versionchanged:: 3.8
467 Prior to Python 3.8, a :keyword:`continue` statement was illegal in the
468 :keyword:`!finally` clause due to a problem with the implementation.
469
470
471 .. _with:
472 .. _as:
473
474 The :keyword:`!with` statement
475 ==============================
476
477 .. index::
478 ! pair: statement; with
479 pair: keyword; as
480 single: as; with statement
481 single: , (comma); with statement
482 single: : (colon); compound statement
483
484 The :keyword:`with` statement is used to wrap the execution of a block with
485 methods defined by a context manager (see section :ref:`context-managers`).
486 This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally`
487 usage patterns to be encapsulated for convenient reuse.
488
489 .. productionlist:: python-grammar
490 with_stmt: "with" ( "(" `with_stmt_contents` ","? ")" | `with_stmt_contents` ) ":" `suite`
491 with_stmt_contents: `with_item` ("," `with_item`)*
492 with_item: `expression` ["as" `target`]
493
494 The execution of the :keyword:`with` statement with one "item" proceeds as follows:
495
496 #. The context expression (the expression given in the
497 :token:`~python-grammar:with_item`) is evaluated to obtain a context manager.
498
499 #. The context manager's :meth:`~object.__enter__` is loaded for later use.
500
501 #. The context manager's :meth:`~object.__exit__` is loaded for later use.
502
503 #. The context manager's :meth:`~object.__enter__` method is invoked.
504
505 #. If a target was included in the :keyword:`with` statement, the return value
506 from :meth:`~object.__enter__` is assigned to it.
507
508 .. note::
509
510 The :keyword:`with` statement guarantees that if the :meth:`~object.__enter__`
511 method returns without an error, then :meth:`~object.__exit__` will always be
512 called. Thus, if an error occurs during the assignment to the target list,
513 it will be treated the same as an error occurring within the suite would
514 be. See step 7 below.
515
516 #. The suite is executed.
517
518 #. The context manager's :meth:`~object.__exit__` method is invoked. If an exception
519 caused the suite to be exited, its type, value, and traceback are passed as
520 arguments to :meth:`~object.__exit__`. Otherwise, three :const:`None` arguments are
521 supplied.
522
523 If the suite was exited due to an exception, and the return value from the
524 :meth:`~object.__exit__` method was false, the exception is reraised. If the return
525 value was true, the exception is suppressed, and execution continues with the
526 statement following the :keyword:`with` statement.
527
528 If the suite was exited for any reason other than an exception, the return
529 value from :meth:`~object.__exit__` is ignored, and execution proceeds at the normal
530 location for the kind of exit that was taken.
531
532 The following code::
533
534 with EXPRESSION as TARGET:
535 SUITE
536
537 is semantically equivalent to::
538
539 manager = (EXPRESSION)
540 enter = type(manager).__enter__
541 exit = type(manager).__exit__
542 value = enter(manager)
543 hit_except = False
544
545 try:
546 TARGET = value
547 SUITE
548 except:
549 hit_except = True
550 if not exit(manager, *sys.exc_info()):
551 raise
552 finally:
553 if not hit_except:
554 exit(manager, None, None, None)
555
556 With more than one item, the context managers are processed as if multiple
557 :keyword:`with` statements were nested::
558
559 with A() as a, B() as b:
560 SUITE
561
562 is semantically equivalent to::
563
564 with A() as a:
565 with B() as b:
566 SUITE
567
568 You can also write multi-item context managers in multiple lines if
569 the items are surrounded by parentheses. For example::
570
571 with (
572 A() as a,
573 B() as b,
574 ):
575 SUITE
576
577 .. versionchanged:: 3.1
578 Support for multiple context expressions.
579
580 .. versionchanged:: 3.10
581 Support for using grouping parentheses to break the statement in multiple lines.
582
583 .. seealso::
584
585 :pep:`343` - The "with" statement
586 The specification, background, and examples for the Python :keyword:`with`
587 statement.
588
589 .. _match:
590 .. _case:
591
592 The :keyword:`!match` statement
593 ===============================
594
595 .. index::
596 ! pair: statement; match
597 ! pair: keyword; case
598 ! single: pattern matching
599 pair: keyword; if
600 pair: keyword; as
601 pair: match; case
602 single: as; match statement
603 single: : (colon); compound statement
604
605 .. versionadded:: 3.10
606
607 The match statement is used for pattern matching. Syntax:
608
609 .. productionlist:: python-grammar
610 match_stmt: 'match' `subject_expr` ":" NEWLINE INDENT `case_block`+ DEDENT
611 subject_expr: `star_named_expression` "," `star_named_expressions`?
612 : | `named_expression`
613 case_block: 'case' `patterns` [`guard`] ":" `block`
614
615 .. note::
616 This section uses single quotes to denote
617 :ref:`soft keywords <soft-keywords>`.
618
619 Pattern matching takes a pattern as input (following ``case``) and a subject
620 value (following ``match``). The pattern (which may contain subpatterns) is
621 matched against the subject value. The outcomes are:
622
623 * A match success or failure (also termed a pattern success or failure).
624
625 * Possible binding of matched values to a name. The prerequisites for this are
626 further discussed below.
627
628 The ``match`` and ``case`` keywords are :ref:`soft keywords <soft-keywords>`.
629
630 .. seealso::
631
632 * :pep:`634` -- Structural Pattern Matching: Specification
633 * :pep:`636` -- Structural Pattern Matching: Tutorial
634
635
636 Overview
637 --------
638
639 Here's an overview of the logical flow of a match statement:
640
641
642 #. The subject expression ``subject_expr`` is evaluated and a resulting subject
643 value obtained. If the subject expression contains a comma, a tuple is
644 constructed using :ref:`the standard rules <typesseq-tuple>`.
645
646 #. Each pattern in a ``case_block`` is attempted to match with the subject value. The
647 specific rules for success or failure are described below. The match attempt can also
648 bind some or all of the standalone names within the pattern. The precise
649 pattern binding rules vary per pattern type and are
650 specified below. **Name bindings made during a successful pattern match
651 outlive the executed block and can be used after the match statement**.
652
653 .. note::
654
655 During failed pattern matches, some subpatterns may succeed. Do not
656 rely on bindings being made for a failed match. Conversely, do not
657 rely on variables remaining unchanged after a failed match. The exact
658 behavior is dependent on implementation and may vary. This is an
659 intentional decision made to allow different implementations to add
660 optimizations.
661
662 #. If the pattern succeeds, the corresponding guard (if present) is evaluated. In
663 this case all name bindings are guaranteed to have happened.
664
665 * If the guard evaluates as true or is missing, the ``block`` inside
666 ``case_block`` is executed.
667
668 * Otherwise, the next ``case_block`` is attempted as described above.
669
670 * If there are no further case blocks, the match statement is completed.
671
672 .. note::
673
674 Users should generally never rely on a pattern being evaluated. Depending on
675 implementation, the interpreter may cache values or use other optimizations
676 which skip repeated evaluations.
677
678 A sample match statement::
679
680 >>> flag = False
681 >>> match (100, 200):
682 ... case (100, 300): # Mismatch: 200 != 300
683 ... print('Case 1')
684 ... case (100, 200) if flag: # Successful match, but guard fails
685 ... print('Case 2')
686 ... case (100, y): # Matches and binds y to 200
687 ... print(f'Case 3, y: {y}')
688 ... case _: # Pattern not attempted
689 ... print('Case 4, I match anything!')
690 ...
691 Case 3, y: 200
692
693
694 In this case, ``if flag`` is a guard. Read more about that in the next section.
695
696 Guards
697 ------
698
699 .. index:: ! guard
700
701 .. productionlist:: python-grammar
702 guard: "if" `named_expression`
703
704 A ``guard`` (which is part of the ``case``) must succeed for code inside
705 the ``case`` block to execute. It takes the form: :keyword:`if` followed by an
706 expression.
707
708
709 The logical flow of a ``case`` block with a ``guard`` follows:
710
711 #. Check that the pattern in the ``case`` block succeeded. If the pattern
712 failed, the ``guard`` is not evaluated and the next ``case`` block is
713 checked.
714
715 #. If the pattern succeeded, evaluate the ``guard``.
716
717 * If the ``guard`` condition evaluates as true, the case block is
718 selected.
719
720 * If the ``guard`` condition evaluates as false, the case block is not
721 selected.
722
723 * If the ``guard`` raises an exception during evaluation, the exception
724 bubbles up.
725
726 Guards are allowed to have side effects as they are expressions. Guard
727 evaluation must proceed from the first to the last case block, one at a time,
728 skipping case blocks whose pattern(s) don't all succeed. (I.e.,
729 guard evaluation must happen in order.) Guard evaluation must stop once a case
730 block is selected.
731
732
733 .. _irrefutable_case:
734
735 Irrefutable Case Blocks
736 -----------------------
737
738 .. index:: irrefutable case block, case block
739
740 An irrefutable case block is a match-all case block. A match statement may have
741 at most one irrefutable case block, and it must be last.
742
743 A case block is considered irrefutable if it has no guard and its pattern is
744 irrefutable. A pattern is considered irrefutable if we can prove from its
745 syntax alone that it will always succeed. Only the following patterns are
746 irrefutable:
747
748 * :ref:`as-patterns` whose left-hand side is irrefutable
749
750 * :ref:`or-patterns` containing at least one irrefutable pattern
751
752 * :ref:`capture-patterns`
753
754 * :ref:`wildcard-patterns`
755
756 * parenthesized irrefutable patterns
757
758
759 Patterns
760 --------
761
762 .. index::
763 single: ! patterns
764 single: AS pattern, OR pattern, capture pattern, wildcard pattern
765
766 .. note::
767 This section uses grammar notations beyond standard EBNF:
768
769 * the notation ``SEP.RULE+`` is shorthand for ``RULE (SEP RULE)*``
770
771 * the notation ``!RULE`` is shorthand for a negative lookahead assertion
772
773
774 The top-level syntax for ``patterns`` is:
775
776 .. productionlist:: python-grammar
777 patterns: `open_sequence_pattern` | `pattern`
778 pattern: `as_pattern` | `or_pattern`
779 closed_pattern: | `literal_pattern`
780 : | `capture_pattern`
781 : | `wildcard_pattern`
782 : | `value_pattern`
783 : | `group_pattern`
784 : | `sequence_pattern`
785 : | `mapping_pattern`
786 : | `class_pattern`
787
788 The descriptions below will include a description "in simple terms" of what a pattern
789 does for illustration purposes (credits to Raymond Hettinger for a document that
790 inspired most of the descriptions). Note that these descriptions are purely for
791 illustration purposes and **may not** reflect
792 the underlying implementation. Furthermore, they do not cover all valid forms.
793
794
795 .. _or-patterns:
796
797 OR Patterns
798 ^^^^^^^^^^^
799
800 An OR pattern is two or more patterns separated by vertical
801 bars ``|``. Syntax:
802
803 .. productionlist:: python-grammar
804 or_pattern: "|".`closed_pattern`+
805
806 Only the final subpattern may be :ref:`irrefutable <irrefutable_case>`, and each
807 subpattern must bind the same set of names to avoid ambiguity.
808
809 An OR pattern matches each of its subpatterns in turn to the subject value,
810 until one succeeds. The OR pattern is then considered successful. Otherwise,
811 if none of the subpatterns succeed, the OR pattern fails.
812
813 In simple terms, ``P1 | P2 | ...`` will try to match ``P1``, if it fails it will try to
814 match ``P2``, succeeding immediately if any succeeds, failing otherwise.
815
816 .. _as-patterns:
817
818 AS Patterns
819 ^^^^^^^^^^^
820
821 An AS pattern matches an OR pattern on the left of the :keyword:`as`
822 keyword against a subject. Syntax:
823
824 .. productionlist:: python-grammar
825 as_pattern: `or_pattern` "as" `capture_pattern`
826
827 If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds
828 the subject to the name on the right of the as keyword and succeeds.
829 ``capture_pattern`` cannot be a ``_``.
830
831 In simple terms ``P as NAME`` will match with ``P``, and on success it will
832 set ``NAME = <subject>``.
833
834
835 .. _literal-patterns:
836
837 Literal Patterns
838 ^^^^^^^^^^^^^^^^
839
840 A literal pattern corresponds to most
841 :ref:`literals <literals>` in Python. Syntax:
842
843 .. productionlist:: python-grammar
844 literal_pattern: `signed_number`
845 : | `signed_number` "+" NUMBER
846 : | `signed_number` "-" NUMBER
847 : | `strings`
848 : | "None"
849 : | "True"
850 : | "False"
851 signed_number: ["-"] NUMBER
852
853 The rule ``strings`` and the token ``NUMBER`` are defined in the
854 :doc:`standard Python grammar <./grammar>`. Triple-quoted strings are
855 supported. Raw strings and byte strings are supported. :ref:`f-strings` are
856 not supported.
857
858 The forms ``signed_number '+' NUMBER`` and ``signed_number '-' NUMBER`` are
859 for expressing :ref:`complex numbers <imaginary>`; they require a real number
860 on the left and an imaginary number on the right. E.g. ``3 + 4j``.
861
862 In simple terms, ``LITERAL`` will succeed only if ``<subject> == LITERAL``. For
863 the singletons ``None``, ``True`` and ``False``, the :keyword:`is` operator is used.
864
865 .. _capture-patterns:
866
867 Capture Patterns
868 ^^^^^^^^^^^^^^^^
869
870 A capture pattern binds the subject value to a name.
871 Syntax:
872
873 .. productionlist:: python-grammar
874 capture_pattern: !'_' NAME
875
876 A single underscore ``_`` is not a capture pattern (this is what ``!'_'``
877 expresses). It is instead treated as a
878 :token:`~python-grammar:wildcard_pattern`.
879
880 In a given pattern, a given name can only be bound once. E.g.
881 ``case x, x: ...`` is invalid while ``case [x] | x: ...`` is allowed.
882
883 Capture patterns always succeed. The binding follows scoping rules
884 established by the assignment expression operator in :pep:`572`; the
885 name becomes a local variable in the closest containing function scope unless
886 there's an applicable :keyword:`global` or :keyword:`nonlocal` statement.
887
888 In simple terms ``NAME`` will always succeed and it will set ``NAME = <subject>``.
889
890 .. _wildcard-patterns:
891
892 Wildcard Patterns
893 ^^^^^^^^^^^^^^^^^
894
895 A wildcard pattern always succeeds (matches anything)
896 and binds no name. Syntax:
897
898 .. productionlist:: python-grammar
899 wildcard_pattern: '_'
900
901 ``_`` is a :ref:`soft keyword <soft-keywords>` within any pattern,
902 but only within patterns. It is an identifier, as usual, even within
903 ``match`` subject expressions, ``guard``\ s, and ``case`` blocks.
904
905 In simple terms, ``_`` will always succeed.
906
907 .. _value-patterns:
908
909 Value Patterns
910 ^^^^^^^^^^^^^^
911
912 A value pattern represents a named value in Python.
913 Syntax:
914
915 .. productionlist:: python-grammar
916 value_pattern: `attr`
917 attr: `name_or_attr` "." NAME
918 name_or_attr: `attr` | NAME
919
920 The dotted name in the pattern is looked up using standard Python
921 :ref:`name resolution rules <resolve_names>`. The pattern succeeds if the
922 value found compares equal to the subject value (using the ``==`` equality
923 operator).
924
925 In simple terms ``NAME1.NAME2`` will succeed only if ``<subject> == NAME1.NAME2``
926
927 .. note::
928
929 If the same value occurs multiple times in the same match statement, the
930 interpreter may cache the first value found and reuse it rather than repeat
931 the same lookup. This cache is strictly tied to a given execution of a
932 given match statement.
933
934 .. _group-patterns:
935
936 Group Patterns
937 ^^^^^^^^^^^^^^
938
939 A group pattern allows users to add parentheses around patterns to
940 emphasize the intended grouping. Otherwise, it has no additional syntax.
941 Syntax:
942
943 .. productionlist:: python-grammar
944 group_pattern: "(" `pattern` ")"
945
946 In simple terms ``(P)`` has the same effect as ``P``.
947
948 .. _sequence-patterns:
949
950 Sequence Patterns
951 ^^^^^^^^^^^^^^^^^
952
953 A sequence pattern contains several subpatterns to be matched against sequence elements.
954 The syntax is similar to the unpacking of a list or tuple.
955
956 .. productionlist:: python-grammar
957 sequence_pattern: "[" [`maybe_sequence_pattern`] "]"
958 : | "(" [`open_sequence_pattern`] ")"
959 open_sequence_pattern: `maybe_star_pattern` "," [`maybe_sequence_pattern`]
960 maybe_sequence_pattern: ",".`maybe_star_pattern`+ ","?
961 maybe_star_pattern: `star_pattern` | `pattern`
962 star_pattern: "*" (`capture_pattern` | `wildcard_pattern`)
963
964 There is no difference if parentheses or square brackets
965 are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ).
966
967 .. note::
968 A single pattern enclosed in parentheses without a trailing comma
969 (e.g. ``(3 | 4)``) is a :ref:`group pattern <group-patterns>`.
970 While a single pattern enclosed in square brackets (e.g. ``[3 | 4]``) is
971 still a sequence pattern.
972
973 At most one star subpattern may be in a sequence pattern. The star subpattern
974 may occur in any position. If no star subpattern is present, the sequence
975 pattern is a fixed-length sequence pattern; otherwise it is a variable-length
976 sequence pattern.
977
978 The following is the logical flow for matching a sequence pattern against a
979 subject value:
980
981 #. If the subject value is not a sequence [#]_, the sequence pattern
982 fails.
983
984 #. If the subject value is an instance of ``str``, ``bytes`` or ``bytearray``
985 the sequence pattern fails.
986
987 #. The subsequent steps depend on whether the sequence pattern is fixed or
988 variable-length.
989
990 If the sequence pattern is fixed-length:
991
992 #. If the length of the subject sequence is not equal to the number of
993 subpatterns, the sequence pattern fails
994
995 #. Subpatterns in the sequence pattern are matched to their corresponding
996 items in the subject sequence from left to right. Matching stops as soon
997 as a subpattern fails. If all subpatterns succeed in matching their
998 corresponding item, the sequence pattern succeeds.
999
1000 Otherwise, if the sequence pattern is variable-length:
1001
1002 #. If the length of the subject sequence is less than the number of non-star
1003 subpatterns, the sequence pattern fails.
1004
1005 #. The leading non-star subpatterns are matched to their corresponding items
1006 as for fixed-length sequences.
1007
1008 #. If the previous step succeeds, the star subpattern matches a list formed
1009 of the remaining subject items, excluding the remaining items
1010 corresponding to non-star subpatterns following the star subpattern.
1011
1012 #. Remaining non-star subpatterns are matched to their corresponding subject
1013 items, as for a fixed-length sequence.
1014
1015 .. note:: The length of the subject sequence is obtained via
1016 :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be
1017 cached by the interpreter in a similar manner as
1018 :ref:`value patterns <value-patterns>`.
1019
1020
1021 In simple terms ``[P1, P2, P3,`` ... ``, P<N>]`` matches only if all the following
1022 happens:
1023
1024 * check ``<subject>`` is a sequence
1025 * ``len(subject) == <N>``
1026 * ``P1`` matches ``<subject>[0]`` (note that this match can also bind names)
1027 * ``P2`` matches ``<subject>[1]`` (note that this match can also bind names)
1028 * ... and so on for the corresponding pattern/element.
1029
1030 .. _mapping-patterns:
1031
1032 Mapping Patterns
1033 ^^^^^^^^^^^^^^^^
1034
1035 A mapping pattern contains one or more key-value patterns. The syntax is
1036 similar to the construction of a dictionary.
1037 Syntax:
1038
1039 .. productionlist:: python-grammar
1040 mapping_pattern: "{" [`items_pattern`] "}"
1041 items_pattern: ",".`key_value_pattern`+ ","?
1042 key_value_pattern: (`literal_pattern` | `value_pattern`) ":" `pattern`
1043 : | `double_star_pattern`
1044 double_star_pattern: "**" `capture_pattern`
1045
1046 At most one double star pattern may be in a mapping pattern. The double star
1047 pattern must be the last subpattern in the mapping pattern.
1048
1049 Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will
1050 raise a :exc:`SyntaxError`. Two keys that otherwise have the same value will
1051 raise a :exc:`ValueError` at runtime.
1052
1053 The following is the logical flow for matching a mapping pattern against a
1054 subject value:
1055
1056 #. If the subject value is not a mapping [#]_,the mapping pattern fails.
1057
1058 #. If every key given in the mapping pattern is present in the subject mapping,
1059 and the pattern for each key matches the corresponding item of the subject
1060 mapping, the mapping pattern succeeds.
1061
1062 #. If duplicate keys are detected in the mapping pattern, the pattern is
1063 considered invalid. A :exc:`SyntaxError` is raised for duplicate literal
1064 values; or a :exc:`ValueError` for named keys of the same value.
1065
1066 .. note:: Key-value pairs are matched using the two-argument form of the mapping
1067 subject's ``get()`` method. Matched key-value pairs must already be present
1068 in the mapping, and not created on-the-fly via :meth:`~object.__missing__`
1069 or :meth:`~object.__getitem__`.
1070
1071 In simple terms ``{KEY1: P1, KEY2: P2, ... }`` matches only if all the following
1072 happens:
1073
1074 * check ``<subject>`` is a mapping
1075 * ``KEY1 in <subject>``
1076 * ``P1`` matches ``<subject>[KEY1]``
1077 * ... and so on for the corresponding KEY/pattern pair.
1078
1079
1080 .. _class-patterns:
1081
1082 Class Patterns
1083 ^^^^^^^^^^^^^^
1084
1085 A class pattern represents a class and its positional and keyword arguments
1086 (if any). Syntax:
1087
1088 .. productionlist:: python-grammar
1089 class_pattern: `name_or_attr` "(" [`pattern_arguments` ","?] ")"
1090 pattern_arguments: `positional_patterns` ["," `keyword_patterns`]
1091 : | `keyword_patterns`
1092 positional_patterns: ",".`pattern`+
1093 keyword_patterns: ",".`keyword_pattern`+
1094 keyword_pattern: NAME "=" `pattern`
1095
1096 The same keyword should not be repeated in class patterns.
1097
1098 The following is the logical flow for matching a class pattern against a
1099 subject value:
1100
1101 #. If ``name_or_attr`` is not an instance of the builtin :class:`type` , raise
1102 :exc:`TypeError`.
1103
1104 #. If the subject value is not an instance of ``name_or_attr`` (tested via
1105 :func:`isinstance`), the class pattern fails.
1106
1107 #. If no pattern arguments are present, the pattern succeeds. Otherwise,
1108 the subsequent steps depend on whether keyword or positional argument patterns
1109 are present.
1110
1111 For a number of built-in types (specified below), a single positional
1112 subpattern is accepted which will match the entire subject; for these types
1113 keyword patterns also work as for other types.
1114
1115 If only keyword patterns are present, they are processed as follows,
1116 one by one:
1117
1118 I. The keyword is looked up as an attribute on the subject.
1119
1120 * If this raises an exception other than :exc:`AttributeError`, the
1121 exception bubbles up.
1122
1123 * If this raises :exc:`AttributeError`, the class pattern has failed.
1124
1125 * Else, the subpattern associated with the keyword pattern is matched
1126 against the subject's attribute value. If this fails, the class
1127 pattern fails; if this succeeds, the match proceeds to the next keyword.
1128
1129
1130 II. If all keyword patterns succeed, the class pattern succeeds.
1131
1132 If any positional patterns are present, they are converted to keyword
1133 patterns using the :data:`~object.__match_args__` attribute on the class
1134 ``name_or_attr`` before matching:
1135
1136 I. The equivalent of ``getattr(cls, "__match_args__", ())`` is called.
1137
1138 * If this raises an exception, the exception bubbles up.
1139
1140 * If the returned value is not a tuple, the conversion fails and
1141 :exc:`TypeError` is raised.
1142
1143 * If there are more positional patterns than ``len(cls.__match_args__)``,
1144 :exc:`TypeError` is raised.
1145
1146 * Otherwise, positional pattern ``i`` is converted to a keyword pattern
1147 using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must
1148 be a string; if not :exc:`TypeError` is raised.
1149
1150 * If there are duplicate keywords, :exc:`TypeError` is raised.
1151
1152 .. seealso:: :ref:`class-pattern-matching`
1153
1154 II. Once all positional patterns have been converted to keyword patterns,
1155 the match proceeds as if there were only keyword patterns.
1156
1157 For the following built-in types the handling of positional subpatterns is
1158 different:
1159
1160 * :class:`bool`
1161 * :class:`bytearray`
1162 * :class:`bytes`
1163 * :class:`dict`
1164 * :class:`float`
1165 * :class:`frozenset`
1166 * :class:`int`
1167 * :class:`list`
1168 * :class:`set`
1169 * :class:`str`
1170 * :class:`tuple`
1171
1172 These classes accept a single positional argument, and the pattern there is matched
1173 against the whole object rather than an attribute. For example ``int(0|1)`` matches
1174 the value ``0``, but not the value ``0.0``.
1175
1176 In simple terms ``CLS(P1, attr=P2)`` matches only if the following happens:
1177
1178 * ``isinstance(<subject>, CLS)``
1179 * convert ``P1`` to a keyword pattern using ``CLS.__match_args__``
1180 * For each keyword argument ``attr=P2``:
1181
1182 * ``hasattr(<subject>, "attr")``
1183 * ``P2`` matches ``<subject>.attr``
1184
1185 * ... and so on for the corresponding keyword argument/pattern pair.
1186
1187 .. seealso::
1188
1189 * :pep:`634` -- Structural Pattern Matching: Specification
1190 * :pep:`636` -- Structural Pattern Matching: Tutorial
1191
1192
1193 .. index::
1194 single: parameter; function definition
1195
1196 .. _function:
1197 .. _def:
1198
1199 Function definitions
1200 ====================
1201
1202 .. index::
1203 pair: statement; def
1204 pair: function; definition
1205 pair: function; name
1206 pair: name; binding
1207 pair: object; user-defined function
1208 pair: object; function
1209 pair: function; name
1210 pair: name; binding
1211 single: () (parentheses); function definition
1212 single: , (comma); parameter list
1213 single: : (colon); compound statement
1214
1215 A function definition defines a user-defined function object (see section
1216 :ref:`types`):
1217
1218 .. productionlist:: python-grammar
1219 funcdef: [`decorators`] "def" `funcname` [`type_params`] "(" [`parameter_list`] ")"
1220 : ["->" `expression`] ":" `suite`
1221 decorators: `decorator`+
1222 decorator: "@" `assignment_expression` NEWLINE
1223 parameter_list: `defparameter` ("," `defparameter`)* "," "/" ["," [`parameter_list_no_posonly`]]
1224 : | `parameter_list_no_posonly`
1225 parameter_list_no_posonly: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]]
1226 : | `parameter_list_starargs`
1227 parameter_list_starargs: "*" [`star_parameter`] ("," `defparameter`)* ["," [`parameter_star_kwargs`]]
1228 : | "*" ("," `defparameter`)+ ["," [`parameter_star_kwargs`]]
1229 : | `parameter_star_kwargs`
1230 parameter_star_kwargs: "**" `parameter` [","]
1231 parameter: `identifier` [":" `expression`]
1232 star_parameter: `identifier` [":" ["*"] `expression`]
1233 defparameter: `parameter` ["=" `expression`]
1234 funcname: `identifier`
1235
1236
1237 A function definition is an executable statement. Its execution binds the
1238 function name in the current local namespace to a function object (a wrapper
1239 around the executable code for the function). This function object contains a
1240 reference to the current global namespace as the global namespace to be used
1241 when the function is called.
1242
1243 The function definition does not execute the function body; this gets executed
1244 only when the function is called. [#]_
1245
1246 .. index::
1247 single: @ (at); function definition
1248
1249 A function definition may be wrapped by one or more :term:`decorator` expressions.
1250 Decorator expressions are evaluated when the function is defined, in the scope
1251 that contains the function definition. The result must be a callable, which is
1252 invoked with the function object as the only argument. The returned value is
1253 bound to the function name instead of the function object. Multiple decorators
1254 are applied in nested fashion. For example, the following code ::
1255
1256 @f1(arg)
1257 @f2
1258 def func(): pass
1259
1260 is roughly equivalent to ::
1261
1262 def func(): pass
1263 func = f1(arg)(f2(func))
1264
1265 except that the original function is not temporarily bound to the name ``func``.
1266
1267 .. versionchanged:: 3.9
1268 Functions may be decorated with any valid
1269 :token:`~python-grammar:assignment_expression`. Previously, the grammar was
1270 much more restrictive; see :pep:`614` for details.
1271
1272 A list of :ref:`type parameters <type-params>` may be given in square brackets
1273 between the function's name and the opening parenthesis for its parameter list.
1274 This indicates to static type checkers that the function is generic. At runtime,
1275 the type parameters can be retrieved from the function's
1276 :attr:`~function.__type_params__`
1277 attribute. See :ref:`generic-functions` for more.
1278
1279 .. versionchanged:: 3.12
1280 Type parameter lists are new in Python 3.12.
1281
1282 .. index::
1283 triple: default; parameter; value
1284 single: argument; function definition
1285 single: = (equals); function definition
1286
1287 When one or more :term:`parameters <parameter>` have the form *parameter* ``=``
1288 *expression*, the function is said to have "default parameter values." For a
1289 parameter with a default value, the corresponding :term:`argument` may be
1290 omitted from a call, in which
1291 case the parameter's default value is substituted. If a parameter has a default
1292 value, all following parameters up until the "``*``" must also have a default
1293 value --- this is a syntactic restriction that is not expressed by the grammar.
1294
1295 **Default parameter values are evaluated from left to right when the function
1296 definition is executed.** This means that the expression is evaluated once, when
1297 the function is defined, and that the same "pre-computed" value is used for each
1298 call. This is especially important to understand when a default parameter value is a
1299 mutable object, such as a list or a dictionary: if the function modifies the
1300 object (e.g. by appending an item to a list), the default parameter value is in effect
1301 modified. This is generally not what was intended. A way around this is to use
1302 ``None`` as the default, and explicitly test for it in the body of the function,
1303 e.g.::
1304
1305 def whats_on_the_telly(penguin=None):
1306 if penguin is None:
1307 penguin = []
1308 penguin.append("property of the zoo")
1309 return penguin
1310
1311 .. index::
1312 single: / (slash); function definition
1313 single: * (asterisk); function definition
1314 single: **; function definition
1315
1316 Function call semantics are described in more detail in section :ref:`calls`. A
1317 function call always assigns values to all parameters mentioned in the parameter
1318 list, either from positional arguments, from keyword arguments, or from default
1319 values. If the form "``*identifier``" is present, it is initialized to a tuple
1320 receiving any excess positional parameters, defaulting to the empty tuple.
1321 If the form "``**identifier``" is present, it is initialized to a new
1322 ordered mapping receiving any excess keyword arguments, defaulting to a
1323 new empty mapping of the same type. Parameters after "``*``" or
1324 "``*identifier``" are keyword-only parameters and may only be passed
1325 by keyword arguments. Parameters before "``/``" are positional-only parameters
1326 and may only be passed by positional arguments.
1327
1328 .. versionchanged:: 3.8
1329 The ``/`` function parameter syntax may be used to indicate positional-only
1330 parameters. See :pep:`570` for details.
1331
1332 .. index::
1333 pair: function; annotations
1334 single: ->; function annotations
1335 single: : (colon); function annotations
1336
1337 Parameters may have an :term:`annotation <function annotation>` of the form "``: expression``"
1338 following the parameter name. Any parameter may have an annotation, even those of the form
1339 ``*identifier`` or ``**identifier``. (As a special case, parameters of the form
1340 ``*identifier`` may have an annotation "``: *expression``".) Functions may have "return" annotation of
1341 the form "``-> expression``" after the parameter list. These annotations can be
1342 any valid Python expression. The presence of annotations does not change the
1343 semantics of a function. The annotation values are available as values of
1344 a dictionary keyed by the parameters' names in the :attr:`__annotations__`
1345 attribute of the function object. If the ``annotations`` import from
1346 :mod:`__future__` is used, annotations are preserved as strings at runtime which
1347 enables postponed evaluation. Otherwise, they are evaluated when the function
1348 definition is executed. In this case annotations may be evaluated in
1349 a different order than they appear in the source code.
1350
1351 .. versionchanged:: 3.11
1352 Parameters of the form "``*identifier``" may have an annotation
1353 "``: *expression``". See :pep:`646`.
1354
1355 .. index:: pair: lambda; expression
1356
1357 It is also possible to create anonymous functions (functions not bound to a
1358 name), for immediate use in expressions. This uses lambda expressions, described in
1359 section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a
1360 simplified function definition; a function defined in a ":keyword:`def`"
1361 statement can be passed around or assigned to another name just like a function
1362 defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful
1363 since it allows the execution of multiple statements and annotations.
1364
1365 **Programmer's note:** Functions are first-class objects. A "``def``" statement
1366 executed inside a function definition defines a local function that can be
1367 returned or passed around. Free variables used in the nested function can
1368 access the local variables of the function containing the def. See section
1369 :ref:`naming` for details.
1370
1371 .. seealso::
1372
1373 :pep:`3107` - Function Annotations
1374 The original specification for function annotations.
1375
1376 :pep:`484` - Type Hints
1377 Definition of a standard meaning for annotations: type hints.
1378
1379 :pep:`526` - Syntax for Variable Annotations
1380 Ability to type hint variable declarations, including class
1381 variables and instance variables.
1382
1383 :pep:`563` - Postponed Evaluation of Annotations
1384 Support for forward references within annotations by preserving
1385 annotations in a string form at runtime instead of eager evaluation.
1386
1387 :pep:`318` - Decorators for Functions and Methods
1388 Function and method decorators were introduced.
1389 Class decorators were introduced in :pep:`3129`.
1390
1391 .. _class:
1392
1393 Class definitions
1394 =================
1395
1396 .. index::
1397 pair: object; class
1398 pair: statement; class
1399 pair: class; definition
1400 pair: class; name
1401 pair: name; binding
1402 pair: execution; frame
1403 single: inheritance
1404 single: docstring
1405 single: () (parentheses); class definition
1406 single: , (comma); expression list
1407 single: : (colon); compound statement
1408
1409 A class definition defines a class object (see section :ref:`types`):
1410
1411 .. productionlist:: python-grammar
1412 classdef: [`decorators`] "class" `classname` [`type_params`] [`inheritance`] ":" `suite`
1413 inheritance: "(" [`argument_list`] ")"
1414 classname: `identifier`
1415
1416 A class definition is an executable statement. The inheritance list usually
1417 gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so
1418 each item in the list should evaluate to a class object which allows
1419 subclassing. Classes without an inheritance list inherit, by default, from the
1420 base class :class:`object`; hence, ::
1421
1422 class Foo:
1423 pass
1424
1425 is equivalent to ::
1426
1427 class Foo(object):
1428 pass
1429
1430 The class's suite is then executed in a new execution frame (see :ref:`naming`),
1431 using a newly created local namespace and the original global namespace.
1432 (Usually, the suite contains mostly function definitions.) When the class's
1433 suite finishes execution, its execution frame is discarded but its local
1434 namespace is saved. [#]_ A class object is then created using the inheritance
1435 list for the base classes and the saved local namespace for the attribute
1436 dictionary. The class name is bound to this class object in the original local
1437 namespace.
1438
1439 The order in which attributes are defined in the class body is preserved
1440 in the new class's :attr:`~type.__dict__`. Note that this is reliable only right
1441 after the class is created and only for classes that were defined using
1442 the definition syntax.
1443
1444 Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`.
1445
1446 .. index::
1447 single: @ (at); class definition
1448
1449 Classes can also be decorated: just like when decorating functions, ::
1450
1451 @f1(arg)
1452 @f2
1453 class Foo: pass
1454
1455 is roughly equivalent to ::
1456
1457 class Foo: pass
1458 Foo = f1(arg)(f2(Foo))
1459
1460 The evaluation rules for the decorator expressions are the same as for function
1461 decorators. The result is then bound to the class name.
1462
1463 .. versionchanged:: 3.9
1464 Classes may be decorated with any valid
1465 :token:`~python-grammar:assignment_expression`. Previously, the grammar was
1466 much more restrictive; see :pep:`614` for details.
1467
1468 A list of :ref:`type parameters <type-params>` may be given in square brackets
1469 immediately after the class's name.
1470 This indicates to static type checkers that the class is generic. At runtime,
1471 the type parameters can be retrieved from the class's
1472 :attr:`~type.__type_params__` attribute. See :ref:`generic-classes` for more.
1473
1474 .. versionchanged:: 3.12
1475 Type parameter lists are new in Python 3.12.
1476
1477 **Programmer's note:** Variables defined in the class definition are class
1478 attributes; they are shared by instances. Instance attributes can be set in a
1479 method with ``self.name = value``. Both class and instance attributes are
1480 accessible through the notation "``self.name``", and an instance attribute hides
1481 a class attribute with the same name when accessed in this way. Class
1482 attributes can be used as defaults for instance attributes, but using mutable
1483 values there can lead to unexpected results. :ref:`Descriptors <descriptors>`
1484 can be used to create instance variables with different implementation details.
1485
1486
1487 .. seealso::
1488
1489 :pep:`3115` - Metaclasses in Python 3000
1490 The proposal that changed the declaration of metaclasses to the current
1491 syntax, and the semantics for how classes with metaclasses are
1492 constructed.
1493
1494 :pep:`3129` - Class Decorators
1495 The proposal that added class decorators. Function and method decorators
1496 were introduced in :pep:`318`.
1497
1498
1499 .. _async:
1500
1501 Coroutines
1502 ==========
1503
1504 .. versionadded:: 3.5
1505
1506 .. index:: pair: statement; async def
1507 .. _`async def`:
1508
1509 Coroutine function definition
1510 -----------------------------
1511
1512 .. productionlist:: python-grammar
1513 async_funcdef: [`decorators`] "async" "def" `funcname` "(" [`parameter_list`] ")"
1514 : ["->" `expression`] ":" `suite`
1515
1516 .. index::
1517 pair: keyword; async
1518 pair: keyword; await
1519
1520 Execution of Python coroutines can be suspended and resumed at many points
1521 (see :term:`coroutine`). :keyword:`await` expressions, :keyword:`async for` and
1522 :keyword:`async with` can only be used in the body of a coroutine function.
1523
1524 Functions defined with ``async def`` syntax are always coroutine functions,
1525 even if they do not contain ``await`` or ``async`` keywords.
1526
1527 It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the body
1528 of a coroutine function.
1529
1530 An example of a coroutine function::
1531
1532 async def func(param1, param2):
1533 do_stuff()
1534 await some_coroutine()
1535
1536 .. versionchanged:: 3.7
1537 ``await`` and ``async`` are now keywords; previously they were only
1538 treated as such inside the body of a coroutine function.
1539
1540 .. index:: pair: statement; async for
1541 .. _`async for`:
1542
1543 The :keyword:`!async for` statement
1544 -----------------------------------
1545
1546 .. productionlist:: python-grammar
1547 async_for_stmt: "async" `for_stmt`
1548
1549 An :term:`asynchronous iterable` provides an ``__aiter__`` method that directly
1550 returns an :term:`asynchronous iterator`, which can call asynchronous code in
1551 its ``__anext__`` method.
1552
1553 The ``async for`` statement allows convenient iteration over asynchronous
1554 iterables.
1555
1556 The following code::
1557
1558 async for TARGET in ITER:
1559 SUITE
1560 else:
1561 SUITE2
1562
1563 Is semantically equivalent to::
1564
1565 iter = (ITER)
1566 iter = type(iter).__aiter__(iter)
1567 running = True
1568
1569 while running:
1570 try:
1571 TARGET = await type(iter).__anext__(iter)
1572 except StopAsyncIteration:
1573 running = False
1574 else:
1575 SUITE
1576 else:
1577 SUITE2
1578
1579 See also :meth:`~object.__aiter__` and :meth:`~object.__anext__` for details.
1580
1581 It is a :exc:`SyntaxError` to use an ``async for`` statement outside the
1582 body of a coroutine function.
1583
1584
1585 .. index:: pair: statement; async with
1586 .. _`async with`:
1587
1588 The :keyword:`!async with` statement
1589 ------------------------------------
1590
1591 .. productionlist:: python-grammar
1592 async_with_stmt: "async" `with_stmt`
1593
1594 An :term:`asynchronous context manager` is a :term:`context manager` that is
1595 able to suspend execution in its *enter* and *exit* methods.
1596
1597 The following code::
1598
1599 async with EXPRESSION as TARGET:
1600 SUITE
1601
1602 is semantically equivalent to::
1603
1604 manager = (EXPRESSION)
1605 aenter = type(manager).__aenter__
1606 aexit = type(manager).__aexit__
1607 value = await aenter(manager)
1608 hit_except = False
1609
1610 try:
1611 TARGET = value
1612 SUITE
1613 except:
1614 hit_except = True
1615 if not await aexit(manager, *sys.exc_info()):
1616 raise
1617 finally:
1618 if not hit_except:
1619 await aexit(manager, None, None, None)
1620
1621 See also :meth:`~object.__aenter__` and :meth:`~object.__aexit__` for details.
1622
1623 It is a :exc:`SyntaxError` to use an ``async with`` statement outside the
1624 body of a coroutine function.
1625
1626 .. seealso::
1627
1628 :pep:`492` - Coroutines with async and await syntax
1629 The proposal that made coroutines a proper standalone concept in Python,
1630 and added supporting syntax.
1631
1632 .. _type-params:
1633
1634 Type parameter lists
1635 ====================
1636
1637 .. versionadded:: 3.12
1638
1639 .. versionchanged:: 3.13
1640 Support for default values was added (see :pep:`696`).
1641
1642 .. index::
1643 single: type parameters
1644
1645 .. productionlist:: python-grammar
1646 type_params: "[" `type_param` ("," `type_param`)* "]"
1647 type_param: `typevar` | `typevartuple` | `paramspec`
1648 typevar: `identifier` (":" `expression`)? ("=" `expression`)?
1649 typevartuple: "*" `identifier` ("=" `expression`)?
1650 paramspec: "**" `identifier` ("=" `expression`)?
1651
1652 :ref:`Functions <def>` (including :ref:`coroutines <async def>`),
1653 :ref:`classes <class>` and :ref:`type aliases <type>` may
1654 contain a type parameter list::
1655
1656 def max[T](args: list[T]) -> T:
1657 ...
1658
1659 async def amax[T](args: list[T]) -> T:
1660 ...
1661
1662 class Bag[T]:
1663 def __iter__(self) -> Iterator[T]:
1664 ...
1665
1666 def add(self, arg: T) -> None:
1667 ...
1668
1669 type ListOrSet[T] = list[T] | set[T]
1670
1671 Semantically, this indicates that the function, class, or type alias is
1672 generic over a type variable. This information is primarily used by static
1673 type checkers, and at runtime, generic objects behave much like their
1674 non-generic counterparts.
1675
1676 Type parameters are declared in square brackets (``[]``) immediately
1677 after the name of the function, class, or type alias. The type parameters
1678 are accessible within the scope of the generic object, but not elsewhere.
1679 Thus, after a declaration ``def func[T](): pass``, the name ``T`` is not available in
1680 the module scope. Below, the semantics of generic objects are described
1681 with more precision. The scope of type parameters is modeled with a special
1682 function (technically, an :ref:`annotation scope <annotation-scopes>`) that
1683 wraps the creation of the generic object.
1684
1685 Generic functions, classes, and type aliases have a
1686 :attr:`~definition.__type_params__` attribute listing their type parameters.
1687
1688 Type parameters come in three kinds:
1689
1690 * :data:`typing.TypeVar`, introduced by a plain name (e.g., ``T``). Semantically, this
1691 represents a single type to a type checker.
1692 * :data:`typing.TypeVarTuple`, introduced by a name prefixed with a single
1693 asterisk (e.g., ``*Ts``). Semantically, this stands for a tuple of any
1694 number of types.
1695 * :data:`typing.ParamSpec`, introduced by a name prefixed with two asterisks
1696 (e.g., ``**P``). Semantically, this stands for the parameters of a callable.
1697
1698 :data:`typing.TypeVar` declarations can define *bounds* and *constraints* with
1699 a colon (``:``) followed by an expression. A single expression after the colon
1700 indicates a bound (e.g. ``T: int``). Semantically, this means
1701 that the :data:`!typing.TypeVar` can only represent types that are a subtype of
1702 this bound. A parenthesized tuple of expressions after the colon indicates a
1703 set of constraints (e.g. ``T: (str, bytes)``). Each member of the tuple should be a
1704 type (again, this is not enforced at runtime). Constrained type variables can only
1705 take on one of the types in the list of constraints.
1706
1707 For :data:`!typing.TypeVar`\ s declared using the type parameter list syntax,
1708 the bound and constraints are not evaluated when the generic object is created,
1709 but only when the value is explicitly accessed through the attributes ``__bound__``
1710 and ``__constraints__``. To accomplish this, the bounds or constraints are
1711 evaluated in a separate :ref:`annotation scope <annotation-scopes>`.
1712
1713 :data:`typing.TypeVarTuple`\ s and :data:`typing.ParamSpec`\ s cannot have bounds
1714 or constraints.
1715
1716 All three flavors of type parameters can also have a *default value*, which is used
1717 when the type parameter is not explicitly provided. This is added by appending
1718 a single equals sign (``=``) followed by an expression. Like the bounds and
1719 constraints of type variables, the default value is not evaluated when the
1720 object is created, but only when the type parameter's ``__default__`` attribute
1721 is accessed. To this end, the default value is evaluated in a separate
1722 :ref:`annotation scope <annotation-scopes>`. If no default value is specified
1723 for a type parameter, the ``__default__`` attribute is set to the special
1724 sentinel object :data:`typing.NoDefault`.
1725
1726 The following example indicates the full set of allowed type parameter declarations::
1727
1728 def overly_generic[
1729 SimpleTypeVar,
1730 TypeVarWithDefault = int,
1731 TypeVarWithBound: int,
1732 TypeVarWithConstraints: (str, bytes),
1733 *SimpleTypeVarTuple = (int, float),
1734 **SimpleParamSpec = (str, bytearray),
1735 ](
1736 a: SimpleTypeVar,
1737 b: TypeVarWithDefault,
1738 c: TypeVarWithBound,
1739 d: Callable[SimpleParamSpec, TypeVarWithConstraints],
1740 *e: SimpleTypeVarTuple,
1741 ): ...
1742
1743 .. _generic-functions:
1744
1745 Generic functions
1746 -----------------
1747
1748 Generic functions are declared as follows::
1749
1750 def func[T](arg: T): ...
1751
1752 This syntax is equivalent to::
1753
1754 annotation-def TYPE_PARAMS_OF_func():
1755 T = typing.TypeVar("T")
1756 def func(arg: T): ...
1757 func.__type_params__ = (T,)
1758 return func
1759 func = TYPE_PARAMS_OF_func()
1760
1761 Here ``annotation-def`` indicates an :ref:`annotation scope <annotation-scopes>`,
1762 which is not actually bound to any name at runtime. (One
1763 other liberty is taken in the translation: the syntax does not go through
1764 attribute access on the :mod:`typing` module, but creates an instance of
1765 :data:`typing.TypeVar` directly.)
1766
1767 The annotations of generic functions are evaluated within the annotation scope
1768 used for declaring the type parameters, but the function's defaults and
1769 decorators are not.
1770
1771 The following example illustrates the scoping rules for these cases,
1772 as well as for additional flavors of type parameters::
1773
1774 @decorator
1775 def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):
1776 ...
1777
1778 Except for the :ref:`lazy evaluation <lazy-evaluation>` of the
1779 :class:`~typing.TypeVar` bound, this is equivalent to::
1780
1781 DEFAULT_OF_arg = some_default
1782
1783 annotation-def TYPE_PARAMS_OF_func():
1784
1785 annotation-def BOUND_OF_T():
1786 return int
1787 # In reality, BOUND_OF_T() is evaluated only on demand.
1788 T = typing.TypeVar("T", bound=BOUND_OF_T())
1789
1790 Ts = typing.TypeVarTuple("Ts")
1791 P = typing.ParamSpec("P")
1792
1793 def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):
1794 ...
1795
1796 func.__type_params__ = (T, Ts, P)
1797 return func
1798 func = decorator(TYPE_PARAMS_OF_func())
1799
1800 The capitalized names like ``DEFAULT_OF_arg`` are not actually
1801 bound at runtime.
1802
1803 .. _generic-classes:
1804
1805 Generic classes
1806 ---------------
1807
1808 Generic classes are declared as follows::
1809
1810 class Bag[T]: ...
1811
1812 This syntax is equivalent to::
1813
1814 annotation-def TYPE_PARAMS_OF_Bag():
1815 T = typing.TypeVar("T")
1816 class Bag(typing.Generic[T]):
1817 __type_params__ = (T,)
1818 ...
1819 return Bag
1820 Bag = TYPE_PARAMS_OF_Bag()
1821
1822 Here again ``annotation-def`` (not a real keyword) indicates an
1823 :ref:`annotation scope <annotation-scopes>`, and the name
1824 ``TYPE_PARAMS_OF_Bag`` is not actually bound at runtime.
1825
1826 Generic classes implicitly inherit from :data:`typing.Generic`.
1827 The base classes and keyword arguments of generic classes are
1828 evaluated within the type scope for the type parameters,
1829 and decorators are evaluated outside that scope. This is illustrated
1830 by this example::
1831
1832 @decorator
1833 class Bag(Base[T], arg=T): ...
1834
1835 This is equivalent to::
1836
1837 annotation-def TYPE_PARAMS_OF_Bag():
1838 T = typing.TypeVar("T")
1839 class Bag(Base[T], typing.Generic[T], arg=T):
1840 __type_params__ = (T,)
1841 ...
1842 return Bag
1843 Bag = decorator(TYPE_PARAMS_OF_Bag())
1844
1845 .. _generic-type-aliases:
1846
1847 Generic type aliases
1848 --------------------
1849
1850 The :keyword:`type` statement can also be used to create a generic type alias::
1851
1852 type ListOrSet[T] = list[T] | set[T]
1853
1854 Except for the :ref:`lazy evaluation <lazy-evaluation>` of the value,
1855 this is equivalent to::
1856
1857 annotation-def TYPE_PARAMS_OF_ListOrSet():
1858 T = typing.TypeVar("T")
1859
1860 annotation-def VALUE_OF_ListOrSet():
1861 return list[T] | set[T]
1862 # In reality, the value is lazily evaluated
1863 return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,))
1864 ListOrSet = TYPE_PARAMS_OF_ListOrSet()
1865
1866 Here, ``annotation-def`` (not a real keyword) indicates an
1867 :ref:`annotation scope <annotation-scopes>`. The capitalized names
1868 like ``TYPE_PARAMS_OF_ListOrSet`` are not actually bound at runtime.
1869
1870 .. rubric:: Footnotes
1871
1872 .. [#] The exception is propagated to the invocation stack unless
1873 there is a :keyword:`finally` clause which happens to raise another
1874 exception. That new exception causes the old one to be lost.
1875
1876 .. [#] In pattern matching, a sequence is defined as one of the following:
1877
1878 * a class that inherits from :class:`collections.abc.Sequence`
1879 * a Python class that has been registered as :class:`collections.abc.Sequence`
1880 * a builtin class that has its (CPython) :c:macro:`Py_TPFLAGS_SEQUENCE` bit set
1881 * a class that inherits from any of the above
1882
1883 The following standard library classes are sequences:
1884
1885 * :class:`array.array`
1886 * :class:`collections.deque`
1887 * :class:`list`
1888 * :class:`memoryview`
1889 * :class:`range`
1890 * :class:`tuple`
1891
1892 .. note:: Subject values of type ``str``, ``bytes``, and ``bytearray``
1893 do not match sequence patterns.
1894
1895 .. [#] In pattern matching, a mapping is defined as one of the following:
1896
1897 * a class that inherits from :class:`collections.abc.Mapping`
1898 * a Python class that has been registered as :class:`collections.abc.Mapping`
1899 * a builtin class that has its (CPython) :c:macro:`Py_TPFLAGS_MAPPING` bit set
1900 * a class that inherits from any of the above
1901
1902 The standard library classes :class:`dict` and :class:`types.MappingProxyType`
1903 are mappings.
1904
1905 .. [#] A string literal appearing as the first statement in the function body is
1906 transformed into the function's :attr:`~function.__doc__` attribute and
1907 therefore the function's :term:`docstring`.
1908
1909 .. [#] A string literal appearing as the first statement in the class body is
1910 transformed into the namespace's :attr:`~type.__doc__` item and therefore
1911 the class's :term:`docstring`.