blob: 8e680812706841046d704c51cab393a0be8c3087 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _compound:
2
3*******************
4Compound statements
5*******************
6
7.. index:: pair: compound; statement
8
9Compound statements contain (groups of) other statements; they affect or control
10the execution of those other statements in some way. In general, compound
11statements span multiple lines, although in simple incarnations a whole compound
12statement may be contained in one line.
13
14The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement
15traditional control flow constructs. :keyword:`try` specifies exception
Georg Brandl02c30562007-09-07 17:52:53 +000016handlers and/or cleanup code for a group of statements, while the
17:keyword:`with` statement allows the execution of initialization and
18finalization code around a block of code. Function and class definitions are
19also syntactically compound statements.
Georg Brandl116aa622007-08-15 14:28:22 +000020
21.. index::
22 single: clause
23 single: suite
Serhiy Storchaka913876d2018-10-28 13:41:26 +020024 single: ; (semicolon)
Georg Brandl116aa622007-08-15 14:28:22 +000025
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070026A compound statement consists of one or more 'clauses.' A clause consists of a
Georg Brandl116aa622007-08-15 14:28:22 +000027header and a 'suite.' The clause headers of a particular compound statement are
28all at the same indentation level. Each clause header begins with a uniquely
29identifying keyword and ends with a colon. A suite is a group of statements
30controlled by a clause. A suite can be one or more semicolon-separated simple
31statements on the same line as the header, following the header's colon, or it
32can be one or more indented statements on subsequent lines. Only the latter
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070033form of a suite can contain nested compound statements; the following is illegal,
Georg Brandl116aa622007-08-15 14:28:22 +000034mostly because it wouldn't be clear to which :keyword:`if` clause a following
Georg Brandl02c30562007-09-07 17:52:53 +000035:keyword:`else` clause would belong::
Georg Brandl116aa622007-08-15 14:28:22 +000036
Georg Brandl6911e3c2007-09-04 07:15:32 +000037 if test1: if test2: print(x)
Georg Brandl116aa622007-08-15 14:28:22 +000038
39Also note that the semicolon binds tighter than the colon in this context, so
Georg Brandl6911e3c2007-09-04 07:15:32 +000040that in the following example, either all or none of the :func:`print` calls are
41executed::
Georg Brandl116aa622007-08-15 14:28:22 +000042
Georg Brandl6911e3c2007-09-04 07:15:32 +000043 if x < y < z: print(x); print(y); print(z)
Georg Brandl116aa622007-08-15 14:28:22 +000044
45Summarizing:
46
Victor Stinner8af239e2020-09-18 09:10:15 +020047
48.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +000049 compound_stmt: `if_stmt`
50 : | `while_stmt`
51 : | `for_stmt`
52 : | `try_stmt`
53 : | `with_stmt`
Daniel F Moisseta22bca62021-03-01 04:08:38 +000054 : | `match_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000055 : | `funcdef`
56 : | `classdef`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -040057 : | `async_with_stmt`
58 : | `async_for_stmt`
59 : | `async_funcdef`
Georg Brandl116aa622007-08-15 14:28:22 +000060 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
69Note that statements always end in a ``NEWLINE`` possibly followed by a
Georg Brandl02c30562007-09-07 17:52:53 +000070``DEDENT``. Also note that optional continuation clauses always begin with a
Georg Brandl116aa622007-08-15 14:28:22 +000071keyword 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
75The formatting of the grammar rules in the following sections places each clause
76on a separate line for clarity.
77
78
79.. _if:
Christian Heimes5b5e81c2007-12-31 16:14:33 +000080.. _elif:
81.. _else:
Georg Brandl116aa622007-08-15 14:28:22 +000082
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020083The :keyword:`!if` statement
84============================
Georg Brandl116aa622007-08-15 14:28:22 +000085
Christian Heimesfaf2f632008-01-06 16:59:19 +000086.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020087 ! statement: if
Christian Heimesfaf2f632008-01-06 16:59:19 +000088 keyword: elif
89 keyword: else
Serhiy Storchaka913876d2018-10-28 13:41:26 +020090 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +000091
92The :keyword:`if` statement is used for conditional execution:
93
Victor Stinner8af239e2020-09-18 09:10:15 +020094.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -080095 if_stmt: "if" `assignment_expression` ":" `suite`
96 : ("elif" `assignment_expression` ":" `suite`)*
Georg Brandl116aa622007-08-15 14:28:22 +000097 : ["else" ":" `suite`]
98
Georg Brandl116aa622007-08-15 14:28:22 +000099It selects exactly one of the suites by evaluating the expressions one by one
100until one is found to be true (see section :ref:`booleans` for the definition of
101true 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
103false, the suite of the :keyword:`else` clause, if present, is executed.
104
105
106.. _while:
107
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200108The :keyword:`!while` statement
109===============================
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200112 ! statement: while
Georg Brandl02c30562007-09-07 17:52:53 +0000113 keyword: else
Georg Brandl116aa622007-08-15 14:28:22 +0000114 pair: loop; statement
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200115 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117The :keyword:`while` statement is used for repeated execution as long as an
118expression is true:
119
Victor Stinner8af239e2020-09-18 09:10:15 +0200120.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -0800121 while_stmt: "while" `assignment_expression` ":" `suite`
Georg Brandl116aa622007-08-15 14:28:22 +0000122 : ["else" ":" `suite`]
123
Georg Brandl116aa622007-08-15 14:28:22 +0000124This repeatedly tests the expression and, if it is true, executes the first
125suite; if the expression is false (which may be the first time it is tested) the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200126suite of the :keyword:`!else` clause, if present, is executed and the loop
Georg Brandl116aa622007-08-15 14:28:22 +0000127terminates.
128
129.. index::
130 statement: break
131 statement: continue
132
133A :keyword:`break` statement executed in the first suite terminates the loop
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200134without executing the :keyword:`!else` clause's suite. A :keyword:`continue`
Georg Brandl116aa622007-08-15 14:28:22 +0000135statement executed in the first suite skips the rest of the suite and goes back
136to testing the expression.
137
138
139.. _for:
140
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200141The :keyword:`!for` statement
142=============================
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200145 ! statement: for
Georg Brandl02c30562007-09-07 17:52:53 +0000146 keyword: in
147 keyword: else
148 pair: target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000149 pair: loop; statement
Georg Brandl02c30562007-09-07 17:52:53 +0000150 object: sequence
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200151 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153The :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
Victor Stinner8af239e2020-09-18 09:10:15 +0200156.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000157 for_stmt: "for" `target_list` "in" `expression_list` ":" `suite`
158 : ["else" ":" `suite`]
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160The expression list is evaluated once; it should yield an iterable object. An
161iterator is created for the result of the ``expression_list``. The suite is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700162then executed once for each item provided by the iterator, in the order returned
163by the iterator. Each item in turn is assigned to the target list using the
Georg Brandl02c30562007-09-07 17:52:53 +0000164standard rules for assignments (see :ref:`assignment`), and then the suite is
165executed. When the items are exhausted (which is immediately when the sequence
166is empty or an iterator raises a :exc:`StopIteration` exception), the suite in
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200167the :keyword:`!else` clause, if present, is executed, and the loop terminates.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169.. index::
170 statement: break
171 statement: continue
172
173A :keyword:`break` statement executed in the first suite terminates the loop
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200174without executing the :keyword:`!else` clause's suite. A :keyword:`continue`
Georg Brandl116aa622007-08-15 14:28:22 +0000175statement executed in the first suite skips the rest of the suite and continues
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200176with the next item, or with the :keyword:`!else` clause if there is no next
Georg Brandl116aa622007-08-15 14:28:22 +0000177item.
178
Andrés Delfinoe42b7052018-07-26 12:35:23 -0300179The for-loop makes assignments to the variables in the target list.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700180This overwrites all previous assignments to those variables including
181those 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
Zachary Ware2f78b842014-06-03 09:32:40 -0500186 # because i will be overwritten with the next
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700187 # index in the range
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190.. index::
191 builtin: range
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Georg Brandl02c30562007-09-07 17:52:53 +0000193Names in the target list are not deleted when the loop is finished, but if the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700194sequence is empty, they will not have been assigned to at all by the loop. Hint:
Georg Brandl02c30562007-09-07 17:52:53 +0000195the built-in function :func:`range` returns an iterator of integers suitable to
Benjamin Peterson3db5e7b2009-06-03 03:13:30 +0000196emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))``
Georg Brandl02c30562007-09-07 17:52:53 +0000197returns the list ``[0, 1, 2]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Georg Brandle720c0a2009-04-27 16:20:50 +0000199.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201 .. index::
202 single: loop; over mutable sequence
203 single: mutable sequence; loop over
204
205 There is a subtlety when the sequence is being modified by the loop (this can
Andrés Delfino6921ef72018-07-30 15:44:35 -0300206 only occur for mutable sequences, e.g. lists). An internal counter is used
Georg Brandl02c30562007-09-07 17:52:53 +0000207 to keep track of which item is used next, and this is incremented on each
Georg Brandl116aa622007-08-15 14:28:22 +0000208 iteration. When this counter has reached the length of the sequence the loop
209 terminates. This means that if the suite deletes the current (or a previous)
Georg Brandl02c30562007-09-07 17:52:53 +0000210 item from the sequence, the next item will be skipped (since it gets the
211 index of the current item which has already been treated). Likewise, if the
212 suite inserts an item in the sequence before the current item, the current
213 item will be treated again the next time through the loop. This can lead to
214 nasty bugs that can be avoided by making a temporary copy using a slice of
215 the whole sequence, e.g., ::
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Georg Brandl02c30562007-09-07 17:52:53 +0000217 for x in a[:]:
218 if x < 0: a.remove(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220
221.. _try:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000222.. _except:
223.. _finally:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200225The :keyword:`!try` statement
226=============================
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Christian Heimesfaf2f632008-01-06 16:59:19 +0000228.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200229 ! statement: try
Christian Heimesfaf2f632008-01-06 16:59:19 +0000230 keyword: except
231 keyword: finally
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300232 keyword: else
233 keyword: as
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200234 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236The :keyword:`try` statement specifies exception handlers and/or cleanup code
237for a group of statements:
238
Victor Stinner8af239e2020-09-18 09:10:15 +0200239.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -0300240 try_stmt: `try1_stmt` | `try2_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +0000241 try1_stmt: "try" ":" `suite`
Terry Jan Reedy65e3ecb2014-08-23 19:29:47 -0400242 : ("except" [`expression` ["as" `identifier`]] ":" `suite`)+
Georg Brandl116aa622007-08-15 14:28:22 +0000243 : ["else" ":" `suite`]
244 : ["finally" ":" `suite`]
245 try2_stmt: "try" ":" `suite`
246 : "finally" ":" `suite`
247
Christian Heimesfaf2f632008-01-06 16:59:19 +0000248
249The :keyword:`except` clause(s) specify one or more exception handlers. When no
Georg Brandl116aa622007-08-15 14:28:22 +0000250exception occurs in the :keyword:`try` clause, no exception handler is executed.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200251When an exception occurs in the :keyword:`!try` suite, a search for an exception
Georg Brandl116aa622007-08-15 14:28:22 +0000252handler is started. This search inspects the except clauses in turn until one
253is found that matches the exception. An expression-less except clause, if
254present, must be last; it matches any exception. For an except clause with an
255expression, that expression is evaluated, and the clause matches the exception
256if the resulting object is "compatible" with the exception. An object is
257compatible with an exception if it is the class or a base class of the exception
Colin Watsonc95f8bc2020-12-20 18:24:10 +0000258object, or a tuple containing an item that is the class or a base class of
259the exception object.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261If no except clause matches the exception, the search for an exception handler
262continues in the surrounding code and on the invocation stack. [#]_
263
264If the evaluation of an expression in the header of an except clause raises an
265exception, the original search for a handler is canceled and a search starts for
266the new exception in the surrounding code and on the call stack (it is treated
267as if the entire :keyword:`try` statement raised the exception).
268
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300269.. index:: single: as; except clause
270
Georg Brandl116aa622007-08-15 14:28:22 +0000271When a matching except clause is found, the exception is assigned to the target
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200272specified after the :keyword:`!as` keyword in that except clause, if present, and
Georg Brandl02c30562007-09-07 17:52:53 +0000273the except clause's suite is executed. All except clauses must have an
274executable block. When the end of this block is reached, execution continues
275normally after the entire try statement. (This means that if two nested
276handlers exist for the same exception, and the exception occurs in the try
277clause of the inner handler, the outer handler will not handle the exception.)
278
279When an exception has been assigned using ``as target``, it is cleared at the
280end of the except clause. This is as if ::
281
282 except E as N:
283 foo
284
285was translated to ::
286
287 except E as N:
288 try:
289 foo
290 finally:
Georg Brandl02c30562007-09-07 17:52:53 +0000291 del N
292
Benjamin Petersonfb288da2010-06-29 01:27:35 +0000293This means the exception must be assigned to a different name to be able to
294refer to it after the except clause. Exceptions are cleared because with the
295traceback attached to them, they form a reference cycle with the stack frame,
296keeping all locals in that frame alive until the next garbage collection occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298.. index::
299 module: sys
300 object: traceback
301
302Before an except clause's suite is executed, details about the exception are
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700303stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`.
Georg Brandlb30f3302011-01-06 09:23:56 +0000304:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the
305exception instance and a traceback object (see section :ref:`types`) identifying
Géry Ogamd515c612020-12-21 14:13:08 +0100306the point in the program where the exception occurred. The details about the
307exception accessed via :func:`sys.exc_info` are restored to their previous values
308when leaving an exception handler::
309
310 >>> print(sys.exc_info())
311 (None, None, None)
312 >>> try:
313 ... raise TypeError
314 ... except:
315 ... print(sys.exc_info())
316 ... try:
317 ... raise ValueError
318 ... except:
319 ... print(sys.exc_info())
320 ... print(sys.exc_info())
321 ...
322 (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
323 (<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>)
324 (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
325 >>> print(sys.exc_info())
326 (None, None, None)
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328.. index::
329 keyword: else
330 statement: return
331 statement: break
332 statement: continue
333
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200334The optional :keyword:`!else` clause is executed if the control flow leaves the
Andrés Delfinob086c8a2018-11-11 16:33:51 -0300335:keyword:`try` suite, no exception was raised, and no :keyword:`return`,
336:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200337the :keyword:`!else` clause are not handled by the preceding :keyword:`except`
Andrés Delfinob086c8a2018-11-11 16:33:51 -0300338clauses.
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340.. index:: keyword: finally
341
342If :keyword:`finally` is present, it specifies a 'cleanup' handler. The
343:keyword:`try` clause is executed, including any :keyword:`except` and
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200344:keyword:`!else` clauses. If an exception occurs in any of the clauses and is
345not handled, the exception is temporarily saved. The :keyword:`!finally` clause
Mark Dickinson05ee5812012-09-24 20:16:38 +0100346is executed. If there is a saved exception it is re-raised at the end of the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200347:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another
Mark Dickinson05ee5812012-09-24 20:16:38 +0100348exception, the saved exception is set as the context of the new exception.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200349If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break`
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200350or :keyword:`continue` statement, the saved exception is discarded::
Andrew Svetlovf158d862012-08-14 15:38:15 +0300351
Zachary Ware9fafc9f2014-05-06 09:18:17 -0500352 >>> def f():
353 ... try:
354 ... 1/0
355 ... finally:
356 ... return 42
357 ...
358 >>> f()
359 42
Andrew Svetlovf158d862012-08-14 15:38:15 +0300360
361The exception information is not available to the program during execution of
362the :keyword:`finally` clause.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364.. index::
365 statement: return
366 statement: break
367 statement: continue
368
369When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200370executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally`
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200371statement, the :keyword:`finally` clause is also executed 'on the way out.'
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Zachary Ware8edd5322014-05-06 09:07:13 -0500373The return value of a function is determined by the last :keyword:`return`
374statement executed. Since the :keyword:`finally` clause always executes, a
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200375:keyword:`!return` statement executed in the :keyword:`!finally` clause will
Zachary Ware8edd5322014-05-06 09:07:13 -0500376always be the last one executed::
377
378 >>> def foo():
379 ... try:
380 ... return 'try'
381 ... finally:
382 ... return 'finally'
383 ...
384 >>> foo()
385 'finally'
386
Georg Brandl116aa622007-08-15 14:28:22 +0000387Additional information on exceptions can be found in section :ref:`exceptions`,
388and information on using the :keyword:`raise` statement to generate exceptions
389may be found in section :ref:`raise`.
390
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200391.. versionchanged:: 3.8
392 Prior to Python 3.8, a :keyword:`continue` statement was illegal in the
393 :keyword:`finally` clause due to a problem with the implementation.
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396.. _with:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000397.. _as:
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200399The :keyword:`!with` statement
400==============================
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400402.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200403 ! statement: with
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300404 keyword: as
405 single: as; with statement
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200406 single: , (comma); with statement
407 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Georg Brandl116aa622007-08-15 14:28:22 +0000409The :keyword:`with` statement is used to wrap the execution of a block with
Georg Brandl02c30562007-09-07 17:52:53 +0000410methods defined by a context manager (see section :ref:`context-managers`).
411This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally`
412usage patterns to be encapsulated for convenient reuse.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Victor Stinner8af239e2020-09-18 09:10:15 +0200414.. productionlist:: python-grammar
Pablo Galindo7c8e0b02021-01-25 23:15:51 +0000415 with_stmt: "with" ( "(" `with_stmt_contents` ","? ")" | `with_stmt_contents` ) ":" `suite`
416 with_stmt_contents: `with_item` ("," `with_item`)*
Georg Brandl0c315622009-05-25 21:10:36 +0000417 with_item: `expression` ["as" `target`]
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Georg Brandl0c315622009-05-25 21:10:36 +0000419The execution of the :keyword:`with` statement with one "item" proceeds as follows:
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Georg Brandl3387f482010-09-03 22:40:02 +0000421#. The context expression (the expression given in the :token:`with_item`) is
422 evaluated to obtain a context manager.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Géry Ogam226e6e72019-12-30 05:24:51 +0000424#. The context manager's :meth:`__enter__` is loaded for later use.
425
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000426#. The context manager's :meth:`__exit__` is loaded for later use.
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428#. The context manager's :meth:`__enter__` method is invoked.
429
430#. If a target was included in the :keyword:`with` statement, the return value
431 from :meth:`__enter__` is assigned to it.
432
433 .. note::
434
Georg Brandl02c30562007-09-07 17:52:53 +0000435 The :keyword:`with` statement guarantees that if the :meth:`__enter__`
436 method returns without an error, then :meth:`__exit__` will always be
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000437 called. Thus, if an error occurs during the assignment to the target list,
438 it will be treated the same as an error occurring within the suite would
439 be. See step 6 below.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441#. The suite is executed.
442
Georg Brandl02c30562007-09-07 17:52:53 +0000443#. The context manager's :meth:`__exit__` method is invoked. If an exception
Georg Brandl116aa622007-08-15 14:28:22 +0000444 caused the suite to be exited, its type, value, and traceback are passed as
445 arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are
446 supplied.
447
448 If the suite was exited due to an exception, and the return value from the
Georg Brandl02c30562007-09-07 17:52:53 +0000449 :meth:`__exit__` method was false, the exception is reraised. If the return
Georg Brandl116aa622007-08-15 14:28:22 +0000450 value was true, the exception is suppressed, and execution continues with the
451 statement following the :keyword:`with` statement.
452
Georg Brandl02c30562007-09-07 17:52:53 +0000453 If the suite was exited for any reason other than an exception, the return
454 value from :meth:`__exit__` is ignored, and execution proceeds at the normal
455 location for the kind of exit that was taken.
Georg Brandl116aa622007-08-15 14:28:22 +0000456
Géry Ogam226e6e72019-12-30 05:24:51 +0000457The following code::
458
459 with EXPRESSION as TARGET:
460 SUITE
461
462is semantically equivalent to::
463
464 manager = (EXPRESSION)
465 enter = type(manager).__enter__
466 exit = type(manager).__exit__
467 value = enter(manager)
468 hit_except = False
469
470 try:
471 TARGET = value
472 SUITE
473 except:
474 hit_except = True
475 if not exit(manager, *sys.exc_info()):
476 raise
477 finally:
478 if not hit_except:
479 exit(manager, None, None, None)
480
Georg Brandl0c315622009-05-25 21:10:36 +0000481With more than one item, the context managers are processed as if multiple
482:keyword:`with` statements were nested::
483
484 with A() as a, B() as b:
Géry Ogam226e6e72019-12-30 05:24:51 +0000485 SUITE
Georg Brandl0c315622009-05-25 21:10:36 +0000486
Géry Ogam226e6e72019-12-30 05:24:51 +0000487is semantically equivalent to::
Georg Brandl0c315622009-05-25 21:10:36 +0000488
489 with A() as a:
490 with B() as b:
Géry Ogam226e6e72019-12-30 05:24:51 +0000491 SUITE
Georg Brandl0c315622009-05-25 21:10:36 +0000492
Pablo Galindo7c8e0b02021-01-25 23:15:51 +0000493You can also write multi-item context managers in multiple lines if
494the items are surrounded by parentheses. For example::
495
496 with (
497 A() as a,
498 B() as b,
499 ):
500 SUITE
501
Georg Brandl0c315622009-05-25 21:10:36 +0000502.. versionchanged:: 3.1
503 Support for multiple context expressions.
504
Pablo Galindo7c8e0b02021-01-25 23:15:51 +0000505.. versionchanged:: 3.10
506 Support for using grouping parentheses to break the statement in multiple lines.
507
Georg Brandl116aa622007-08-15 14:28:22 +0000508.. seealso::
509
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300510 :pep:`343` - The "with" statement
Georg Brandl116aa622007-08-15 14:28:22 +0000511 The specification, background, and examples for the Python :keyword:`with`
512 statement.
513
Daniel F Moisseta22bca62021-03-01 04:08:38 +0000514.. _match:
515
516The :keyword:`!match` statement
517===============================
518
519.. index::
520 ! statement: match
521 ! keyword: case
522 ! single: pattern matching
523 keyword: if
524 keyword: as
525 pair: match; case
526 single: : (colon); compound statement
527
528.. versionadded:: 3.10
529
530The match statement is used for pattern matching. Syntax:
531
532.. productionlist:: python-grammar
533 match_stmt: 'match' `subject_expr` ":" NEWLINE INDENT `case_block`+ DEDENT
534 subject_expr: `star_named_expression` "," `star_named_expressions`?
535 : | `named_expression`
Ken Jin37a5e222021-04-13 01:03:20 +0800536 case_block: 'case' `patterns` [`guard`] ":" `block`
Daniel F Moisseta22bca62021-03-01 04:08:38 +0000537
538.. note::
539 This section uses single quotes to denote
540 :ref:`soft keywords <soft-keywords>`.
541
542Pattern matching takes a pattern as input (following ``case``) and a subject
543value (following ``match``). The pattern (which may contain subpatterns) is
544matched against the subject value. The outcomes are:
545
546* A match success or failure (also termed a pattern success or failure).
547
548* Possible binding of matched values to a name. The prerequisites for this are
549 further discussed below.
550
551The ``match`` and ``case`` keywords are :ref:`soft keywords <soft-keywords>`.
552
553.. seealso::
554
555 * :pep:`634` -- Structural Pattern Matching: Specification
556 * :pep:`636` -- Structural Pattern Matching: Tutorial
557
558
559Overview
560--------
561
562Here's an overview of the logical flow of a match statement:
563
564
565#. The subject expression ``subject_expr`` is evaluated and a resulting subject
566 value obtained. If the subject expression contains a comma, a tuple is
567 constructed using :ref:`the standard rules <typesseq-tuple>`.
568
569#. Each pattern in a ``case_block`` is attempted to match with the subject value. The
570 specific rules for success or failure are described below. The match attempt can also
571 bind some or all of the standalone names within the pattern. The precise
572 pattern binding rules vary per pattern type and are
573 specified below. **Name bindings made during a successful pattern match
574 outlive the executed block and can be used after the match statement**.
575
576 .. note::
577
578 During failed pattern matches, some subpatterns may succeed. Do not
579 rely on bindings being made for a failed match. Conversely, do not
580 rely on variables remaining unchanged after a failed match. The exact
581 behavior is dependent on implementation and may vary. This is an
582 intentional decision made to allow different implementations to add
583 optimizations.
584
585#. If the pattern succeeds, the corresponding guard (if present) is evaluated. In
586 this case all name bindings are guaranteed to have happened.
587
588 * If the guard evaluates as truthy or missing, the ``block`` inside ``case_block`` is
589 executed.
590
591 * Otherwise, the next ``case_block`` is attempted as described above.
592
593 * If there are no further case blocks, the match statement is completed.
594
595.. note::
596
597 Users should generally never rely on a pattern being evaluated. Depending on
598 implementation, the interpreter may cache values or use other optimizations
599 which skip repeated evaluations.
600
601A sample match statement::
602
603 >>> flag = False
604 >>> match (100, 200):
605 ... case (100, 300): # Mismatch: 200 != 300
606 ... print('Case 1')
607 ... case (100, 200) if flag: # Successful match, but guard fails
608 ... print('Case 2')
609 ... case (100, y): # Matches and binds y to 200
610 ... print(f'Case 3, y: {y}')
611 ... case _: # Pattern not attempted
612 ... print('Case 4, I match anything!')
613 ...
614 Case 3, y: 200
615
616
617In this case, ``if flag`` is a guard. Read more about that in the next section.
618
619Guards
620------
621
622.. index:: ! guard
623
624.. productionlist:: python-grammar
625 guard: "if" `named_expression`
626
627A ``guard`` (which is part of the ``case``) must succeed for code inside
628the ``case`` block to execute. It takes the form: :keyword:`if` followed by an
629expression.
630
631
632The logical flow of a ``case`` block with a ``guard`` follows:
633
634#. Check that the pattern in the ``case`` block succeeded. If the pattern
635 failed, the ``guard`` is not evaluated and the next ``case`` block is
636 checked.
637
638#. If the pattern succeeded, evaluate the ``guard``.
639
640 * If the ``guard`` condition evaluates to "truthy", the case block is
641 selected.
642
643 * If the ``guard`` condition evaluates to "falsy", the case block is not
644 selected.
645
646 * If the ``guard`` raises an exception during evaluation, the exception
647 bubbles up.
648
649Guards are allowed to have side effects as they are expressions. Guard
650evaluation must proceed from the first to the last case block, one at a time,
651skipping case blocks whose pattern(s) don't all succeed. (I.e.,
652guard evaluation must happen in order.) Guard evaluation must stop once a case
653block is selected.
654
655
656.. _irrefutable_case:
657
658Irrefutable Case Blocks
659-----------------------
660
661.. index:: irrefutable case block, case block
662
663An irrefutable case block is a match-all case block. A match statement may have
664at most one irrefutable case block, and it must be last.
665
666A case block is considered irrefutable if it has no guard and its pattern is
667irrefutable. A pattern is considered irrefutable if we can prove from its
668syntax alone that it will always succeed. Only the following patterns are
669irrefutable:
670
671* :ref:`as-patterns` whose left-hand side is irrefutable
672
673* :ref:`or-patterns` containing at least one irrefutable pattern
674
675* :ref:`capture-patterns`
676
677* :ref:`wildcard-patterns`
678
679* parenthesized irrefutable patterns
680
681
682Patterns
683--------
684
685.. index::
686 single: ! patterns
687 single: AS pattern, OR pattern, capture pattern, wildcard pattern
688
689.. note::
690 This section uses grammar notations beyond standard EBNF:
691
692 * the notation ``SEP.RULE+`` is shorthand for ``RULE (SEP RULE)*``
693
694 * the notation ``!RULE`` is shorthand for a negative lookahead assertion
695
696
697The top-level syntax for ``patterns`` is:
698
699.. productionlist:: python-grammar
700 patterns: `open_sequence_pattern` | `pattern`
701 pattern: `as_pattern` | `or_pattern`
702 closed_pattern: | `literal_pattern`
703 : | `capture_pattern`
704 : | `wildcard_pattern`
705 : | `value_pattern`
706 : | `group_pattern`
707 : | `sequence_pattern`
708 : | `mapping_pattern`
709 : | `class_pattern`
710
711The descriptions below will include a description "in simple terms" of what a pattern
712does for illustration purposes (credits to Raymond Hettinger for a document that
713inspired most of the descriptions). Note that these descriptions are purely for
714illustration purposes and **may not** reflect
715the underlying implementation. Furthermore, they do not cover all valid forms.
716
717
718.. _or-patterns:
719
720OR Patterns
721^^^^^^^^^^^
722
723An OR pattern is two or more patterns separated by vertical
724bars ``|``. Syntax:
725
726.. productionlist:: python-grammar
727 or_pattern: "|".`closed_pattern`+
728
729Only the final subpattern may be :ref:`irrefutable <irrefutable_case>`, and each
730subpattern must bind the same set of names to avoid ambiguity.
731
732An OR pattern matches each of its subpatterns in turn to the subject value,
733until one succeeds. The OR pattern is then considered successful. Otherwise,
734if none of the subpatterns succeed, the OR pattern fails.
735
736In simple terms, ``P1 | P2 | ...`` will try to match ``P1``, if it fails it will try to
737match ``P2``, succeeding immediately if any succeeds, failing otherwise.
738
739.. _as-patterns:
740
741AS Patterns
742^^^^^^^^^^^
743
744An AS pattern matches an OR pattern on the left of the :keyword:`as`
745keyword against a subject. Syntax:
746
747.. productionlist:: python-grammar
748 as_pattern: `or_pattern` "as" `capture_pattern`
749
750If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds
751the subject to the name on the right of the as keyword and succeeds.
752``capture_pattern`` cannot be a a ``_``.
753
754In simple terms ``P as NAME`` will match with ``P``, and on success it will
755set ``NAME = <subject>``.
756
757
758.. _literal-patterns:
759
760Literal Patterns
761^^^^^^^^^^^^^^^^
762
763A literal pattern corresponds to most
764:ref:`literals <literals>` in Python. Syntax:
765
766.. productionlist:: python-grammar
767 literal_pattern: `signed_number`
768 : | `signed_number` "+" NUMBER
769 : | `signed_number` "-" NUMBER
770 : | `strings`
771 : | "None"
772 : | "True"
773 : | "False"
774 : | `signed_number`: NUMBER | "-" NUMBER
775
776The rule ``strings`` and the token ``NUMBER`` are defined in the
777:doc:`standard Python grammar <./grammar>`. Triple-quoted strings are
778supported. Raw strings and byte strings are supported. :ref:`f-strings` are
779not supported.
780
781The forms ``signed_number '+' NUMBER`` and ``signed_number '-' NUMBER`` are
782for expressing :ref:`complex numbers <imaginary>`; they require a real number
783on the left and an imaginary number on the right. E.g. ``3 + 4j``.
784
785In simple terms, ``LITERAL`` will succeed only if ``<subject> == LITERAL``. For
786the singletons ``None``, ``True`` and ``False``, the :keyword:`is` operator is used.
787
788.. _capture-patterns:
789
790Capture Patterns
791^^^^^^^^^^^^^^^^
792
793A capture pattern binds the subject value to a name.
794Syntax:
795
796.. productionlist:: python-grammar
797 capture_pattern: !'_' NAME
798
799A single underscore ``_`` is not a capture pattern (this is what ``!'_'``
800expresses). And is instead treated as a :token:`wildcard_pattern`.
801
802In a given pattern, a given name can only be bound once. E.g.
803``case x, x: ...`` is invalid while ``case [x] | x: ...`` is allowed.
804
805Capture patterns always succeed. The binding follows scoping rules
806established by the assignment expression operator in :pep:`572`; the
807name becomes a local variable in the closest containing function scope unless
808there's an applicable :keyword:`global` or :keyword:`nonlocal` statement.
809
810In simple terms ``NAME`` will always succeed and it will set ``NAME = <subject>``.
811
812.. _wildcard-patterns:
813
814Wildcard Patterns
815^^^^^^^^^^^^^^^^^
816
817A wildcard pattern always succeeds (matches anything)
818and binds no name. Syntax:
819
820.. productionlist:: python-grammar
821 wildcard_pattern: '_'
822
823``_`` is a :ref:`soft keyword <soft-keywords>`.
824
825In simple terms, ``_`` will always succeed.
826
827.. _value-patterns:
828
829Value Patterns
830^^^^^^^^^^^^^^
831
832A value pattern represents a named value in Python.
833Syntax:
834
835.. productionlist:: python-grammar
836 value_pattern: `attr`
837 attr: `name_or_attr` "." NAME
838 name_or_attr: `attr` | NAME
839
840The dotted name in the pattern is looked up using standard Python
841:ref:`name resolution rules <resolve_names>`. The pattern succeeds if the
842value found compares equal to the subject value (using the ``==`` equality
843operator).
844
845In simple terms ``NAME1.NAME2`` will succeed only if ``<subject> == NAME1.NAME2``
846
847.. note::
848
849 If the same value occurs multiple times in the same match statement, the
850 interpreter may cache the first value found and reuse it rather than repeat
851 the same lookup. This cache is strictly tied to a given execution of a
852 given match statement.
853
854.. _group-patterns:
855
856Group Patterns
857^^^^^^^^^^^^^^
858
859A group pattern allows users to add parentheses around patterns to
860emphasize the intended grouping. Otherwise, it has no additional syntax.
861Syntax:
862
863.. productionlist:: python-grammar
Ken Jin37a5e222021-04-13 01:03:20 +0800864 group_pattern: "(" `pattern` ")"
Daniel F Moisseta22bca62021-03-01 04:08:38 +0000865
866In simple terms ``(P)`` has the same effect as ``P``.
867
868.. _sequence-patterns:
869
870Sequence Patterns
871^^^^^^^^^^^^^^^^^
872
873A sequence pattern contains several subpatterns to be matched against sequence elements.
874The syntax is similar to the unpacking of a list or tuple.
875
876.. productionlist:: python-grammar
877 sequence_pattern: "[" [`maybe_sequence_pattern`] "]"
878 : | "(" [`open_sequence_pattern`] ")"
879 open_sequence_pattern: `maybe_star_pattern` "," [`maybe_sequence_pattern`]
880 maybe_sequence_pattern: ",".`maybe_star_pattern`+ ","?
881 maybe_star_pattern: `star_pattern` | `pattern`
882 star_pattern: "*" (`capture_pattern` | `wildcard_pattern`)
883
884There is no difference if parentheses or square brackets
885are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ).
886
887.. note::
888 A single pattern enclosed in parentheses without a trailing comma
889 (e.g. ``(3 | 4)``) is a :ref:`group pattern <group-patterns>`.
890 While a single pattern enclosed in square brackets (e.g. ``[3 | 4]``) is
891 still a sequence pattern.
892
893At most one star subpattern may be in a sequence pattern. The star subpattern
894may occur in any position. If no star subpattern is present, the sequence
895pattern is a fixed-length sequence pattern; otherwise it is a variable-length
896sequence pattern.
897
898The following is the logical flow for matching a sequence pattern against a
899subject value:
900
901#. If the subject value is not an instance of a
902 :class:`collections.abc.Sequence` the sequence pattern fails.
903
904#. If the subject value is an instance of ``str``, ``bytes`` or ``bytearray``
905 the sequence pattern fails.
906
907#. The subsequent steps depend on whether the sequence pattern is fixed or
908 variable-length.
909
910 If the sequence pattern is fixed-length:
911
912 #. If the length of the subject sequence is not equal to the number of
913 subpatterns, the sequence pattern fails
914
915 #. Subpatterns in the sequence pattern are matched to their corresponding
916 items in the subject sequence from left to right. Matching stops as soon
917 as a subpattern fails. If all subpatterns succeed in matching their
918 corresponding item, the sequence pattern succeeds.
919
920 Otherwise, if the sequence pattern is variable-length:
921
922 #. If the length of the subject sequence is less than the number of non-star
923 subpatterns, the sequence pattern fails.
924
925 #. The leading non-star subpatterns are matched to their corresponding items
926 as for fixed-length sequences.
927
928 #. If the previous step succeeds, the star subpattern matches a list formed
929 of the remaining subject items, excluding the remaining items
930 corresponding to non-star subpatterns following the star subpattern.
931
932 #. Remaining non-star subpatterns are matched to their corresponding subject
933 items, as for a fixed-length sequence.
934
935 .. note:: The length of the subject sequence is obtained via
936 :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be
937 cached by the interpreter in a similar manner as
938 :ref:`value patterns <value-patterns>`.
939
940
941In simple terms ``[P1, P2, P3,`` ... ``, P<N>]`` matches only if all the following
942happens:
943
944* ``isinstance(<subject>, collections.abc.Sequence)``
945* ``len(subject) == <N>``
946* ``P1`` matches ``<subject>[0]`` (note that this match can also bind names)
947* ``P2`` matches ``<subject>[1]`` (note that this match can also bind names)
948* ... and so on for the corresponding pattern/element.
949
950.. _mapping-patterns:
951
952Mapping Patterns
953^^^^^^^^^^^^^^^^
954
955A mapping pattern contains one or more key-value patterns. The syntax is
956similar to the construction of a dictionary.
957Syntax:
958
959.. productionlist:: python-grammar
960 mapping_pattern: "{" [`items_pattern`] "}"
961 items_pattern: ",".`key_value_pattern`+ ","?
962 key_value_pattern: (`literal_pattern` | `value_pattern`) ":" `pattern`
963 : | `double_star_pattern`
964 double_star_pattern: "**" `capture_pattern`
965
966At most one double star pattern may be in a mapping pattern. The double star
967pattern must be the last subpattern in the mapping pattern.
968
969Duplicate key values in mapping patterns are disallowed. (If all key patterns
970are literal patterns this is considered a syntax error; otherwise this is a
971runtime error and will raise :exc:`ValueError`.)
972
973The following is the logical flow for matching a mapping pattern against a
974subject value:
975
976#. If the subject value is not an instance of :class:`collections.abc.Mapping`,
977 the mapping pattern fails.
978
979#. If every key given in the mapping pattern is present in the subject mapping,
980 and the pattern for each key matches the corresponding item of the subject
981 mapping, the mapping pattern succeeds.
982
983#. If duplicate keys are detected in the mapping pattern, the pattern is
984 considered invalid and :exc:`ValueError` is raised.
985
986.. note:: Key-value pairs are matched using the two-argument form of the mapping
987 subject's ``get()`` method. Matched key-value pairs must already be present
988 in the mapping, and not created on-the-fly via :meth:`__missing__` or
989 :meth:`__getitem__`.
990
991In simple terms ``{KEY1: P1, KEY2: P2, ... }`` matches only if all the following
992happens:
993
994* ``isinstance(<subject>, collections.abc.Mapping)``
995* ``KEY1 in <subject>``
996* ``P1`` matches ``<subject>[KEY1]``
997* ... and so on for the corresponding KEY/pattern pair.
998
999
1000.. _class-patterns:
1001
1002Class Patterns
1003^^^^^^^^^^^^^^
1004
1005A class pattern represents a class and its positional and keyword arguments
1006(if any). Syntax:
1007
1008.. productionlist:: python-grammar
1009 class_pattern: `name_or_attr` "(" [`pattern_arguments` ","?] ")"
1010 pattern_arguments: `positional_patterns` ["," `keyword_patterns`]
1011 : | `keyword_patterns`
1012 positional_patterns: ",".`pattern`+
1013 keyword_patterns: ",".`keyword_pattern`+
1014 keyword_pattern: NAME "=" `pattern`
1015
1016The same keyword should not be repeated in class patterns.
1017
1018The following is the logical flow for matching a mapping pattern against a
1019subject value:
1020
1021#. If ``name_or_attr`` is not an instance of the builtin :class:`type` , raise
1022 :exc:`TypeError`.
1023
1024#. If the subject value is not an instance of ``name_or_attr`` (tested via
1025 :func:`isinstance`), the class pattern fails.
1026
1027#. If no pattern arguments are present, the pattern succeeds. Otherwise,
1028 the subsequent steps depend on whether keyword or positional argument patterns
1029 are present.
1030
1031 For a number of built-in types (specified below), a single positional
1032 subpattern is accepted which will match the entire subject; for these types
Ken Jin5143fd12021-04-07 00:03:00 +08001033 keyword patterns also work as for other types.
Daniel F Moisseta22bca62021-03-01 04:08:38 +00001034
1035 If only keyword patterns are present, they are processed as follows,
1036 one by one:
1037
1038 I. The keyword is looked up as an attribute on the subject.
1039
1040 * If this raises an exception other than :exc:`AttributeError`, the
1041 exception bubbles up.
1042
1043 * If this raises :exc:`AttributeError`, the class pattern has failed.
1044
1045 * Else, the subpattern associated with the keyword pattern is matched
1046 against the subject's attribute value. If this fails, the class
1047 pattern fails; if this succeeds, the match proceeds to the next keyword.
1048
1049
1050 II. If all keyword patterns succeed, the class pattern succeeds.
1051
1052 If any positional patterns are present, they are converted to keyword
1053 patterns using the :data:`~object.__match_args__` attribute on the class
1054 ``name_or_attr`` before matching:
1055
1056 I. The equivalent of ``getattr(cls, "__match_args__", ()))`` is called.
1057
1058 * If this raises an exception, the exception bubbles up.
1059
Ken Jin5143fd12021-04-07 00:03:00 +08001060 * If the returned value is not a tuple, the conversion fails and
Daniel F Moisseta22bca62021-03-01 04:08:38 +00001061 :exc:`TypeError` is raised.
1062
1063 * If there are more positional patterns than ``len(cls.__match_args__)``,
1064 :exc:`TypeError` is raised.
1065
1066 * Otherwise, positional pattern ``i`` is converted to a keyword pattern
1067 using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must
1068 be a string; if not :exc:`TypeError` is raised.
1069
1070 * If there are duplicate keywords, :exc:`TypeError` is raised.
1071
1072 .. seealso:: :ref:`class-pattern-matching`
1073
1074 II. Once all positional patterns have been converted to keyword patterns,
1075 the match proceeds as if there were only keyword patterns.
1076
1077 For the following built-in types the handling of positional subpatterns is
1078 different:
1079
1080 * :class:`bool`
1081 * :class:`bytearray`
1082 * :class:`bytes`
1083 * :class:`dict`
1084 * :class:`float`
1085 * :class:`frozenset`
1086 * :class:`int`
1087 * :class:`list`
1088 * :class:`set`
1089 * :class:`str`
1090 * :class:`tuple`
1091
1092 These classes accept a single positional argument, and the pattern there is matched
1093 against the whole object rather than an attribute. For example ``int(0|1)`` matches
1094 the value ``0``, but not the values ``0.0`` or ``False``.
1095
1096In simple terms ``CLS(P1, attr=P2)`` matches only if the following happens:
1097
1098* ``isinstance(<subject>, CLS)``
1099* convert ``P1`` to a keyword pattern using ``CLS.__match_args__``
1100* For each keyword argument ``attr=P2``:
1101 * ``hasattr(<subject>, "attr")``
1102 * ``P2`` matches ``<subject>.attr``
1103* ... and so on for the corresponding keyword argument/pattern pair.
1104
1105.. seealso::
1106
1107 * :pep:`634` -- Structural Pattern Matching: Specification
1108 * :pep:`636` -- Structural Pattern Matching: Tutorial
1109
Georg Brandl116aa622007-08-15 14:28:22 +00001110
Chris Jerdonekb4309942012-12-25 14:54:44 -08001111.. index::
1112 single: parameter; function definition
1113
Georg Brandl116aa622007-08-15 14:28:22 +00001114.. _function:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001115.. _def:
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117Function definitions
1118====================
1119
1120.. index::
Georg Brandl116aa622007-08-15 14:28:22 +00001121 statement: def
Christian Heimesfaf2f632008-01-06 16:59:19 +00001122 pair: function; definition
1123 pair: function; name
1124 pair: name; binding
Georg Brandl116aa622007-08-15 14:28:22 +00001125 object: user-defined function
1126 object: function
Georg Brandl02c30562007-09-07 17:52:53 +00001127 pair: function; name
1128 pair: name; binding
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001129 single: () (parentheses); function definition
1130 single: , (comma); parameter list
1131 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133A function definition defines a user-defined function object (see section
1134:ref:`types`):
1135
Victor Stinner8af239e2020-09-18 09:10:15 +02001136.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001137 funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")"
1138 : ["->" `expression`] ":" `suite`
Georg Brandl116aa622007-08-15 14:28:22 +00001139 decorators: `decorator`+
Brandt Bucher8f130532020-03-07 10:23:49 -08001140 decorator: "@" `assignment_expression` NEWLINE
Pablo Galindo29cb21d2019-05-29 22:59:00 +01001141 parameter_list: `defparameter` ("," `defparameter`)* "," "/" ["," [`parameter_list_no_posonly`]]
Pablo Galindob76302d2019-05-29 00:45:32 +01001142 : | `parameter_list_no_posonly`
1143 parameter_list_no_posonly: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]]
1144 : | `parameter_list_starargs`
Robert Collinsdf395992015-08-12 08:00:06 +12001145 parameter_list_starargs: "*" [`parameter`] ("," `defparameter`)* ["," ["**" `parameter` [","]]]
Andrés Delfinocaccca782018-07-07 17:24:46 -03001146 : | "**" `parameter` [","]
Georg Brandl116aa622007-08-15 14:28:22 +00001147 parameter: `identifier` [":" `expression`]
1148 defparameter: `parameter` ["=" `expression`]
1149 funcname: `identifier`
1150
Georg Brandl116aa622007-08-15 14:28:22 +00001151
1152A function definition is an executable statement. Its execution binds the
1153function name in the current local namespace to a function object (a wrapper
1154around the executable code for the function). This function object contains a
1155reference to the current global namespace as the global namespace to be used
1156when the function is called.
1157
1158The function definition does not execute the function body; this gets executed
Georg Brandl3dbca812008-07-23 16:10:53 +00001159only when the function is called. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001160
Christian Heimesdae2a892008-04-19 00:55:37 +00001161.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001162 single: @ (at); function definition
Christian Heimesdae2a892008-04-19 00:55:37 +00001163
Christian Heimesd8654cf2007-12-02 15:22:16 +00001164A function definition may be wrapped by one or more :term:`decorator` expressions.
Georg Brandl116aa622007-08-15 14:28:22 +00001165Decorator expressions are evaluated when the function is defined, in the scope
1166that contains the function definition. The result must be a callable, which is
1167invoked with the function object as the only argument. The returned value is
1168bound to the function name instead of the function object. Multiple decorators
Georg Brandl02c30562007-09-07 17:52:53 +00001169are applied in nested fashion. For example, the following code ::
Georg Brandl116aa622007-08-15 14:28:22 +00001170
1171 @f1(arg)
1172 @f2
1173 def func(): pass
1174
Berker Peksag6cafece2016-08-03 10:17:21 +03001175is roughly equivalent to ::
Georg Brandl116aa622007-08-15 14:28:22 +00001176
1177 def func(): pass
1178 func = f1(arg)(f2(func))
1179
Berker Peksag6cafece2016-08-03 10:17:21 +03001180except that the original function is not temporarily bound to the name ``func``.
1181
Brandt Bucher8f130532020-03-07 10:23:49 -08001182.. versionchanged:: 3.9
1183 Functions may be decorated with any valid :token:`assignment_expression`.
1184 Previously, the grammar was much more restrictive; see :pep:`614` for
1185 details.
1186
Chris Jerdonekb4309942012-12-25 14:54:44 -08001187.. index::
1188 triple: default; parameter; value
1189 single: argument; function definition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001190 single: = (equals); function definition
Georg Brandl116aa622007-08-15 14:28:22 +00001191
Chris Jerdonekb4309942012-12-25 14:54:44 -08001192When one or more :term:`parameters <parameter>` have the form *parameter* ``=``
1193*expression*, the function is said to have "default parameter values." For a
1194parameter with a default value, the corresponding :term:`argument` may be
1195omitted from a call, in which
Georg Brandl116aa622007-08-15 14:28:22 +00001196case the parameter's default value is substituted. If a parameter has a default
Georg Brandl02c30562007-09-07 17:52:53 +00001197value, all following parameters up until the "``*``" must also have a default
1198value --- this is a syntactic restriction that is not expressed by the grammar.
Georg Brandl116aa622007-08-15 14:28:22 +00001199
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001200**Default parameter values are evaluated from left to right when the function
1201definition is executed.** This means that the expression is evaluated once, when
1202the function is defined, and that the same "pre-computed" value is used for each
Andre Delfinob9f6ac92020-07-22 20:58:19 -03001203call. This is especially important to understand when a default parameter value is a
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001204mutable object, such as a list or a dictionary: if the function modifies the
Andre Delfinob9f6ac92020-07-22 20:58:19 -03001205object (e.g. by appending an item to a list), the default parameter value is in effect
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001206modified. This is generally not what was intended. A way around this is to use
1207``None`` as the default, and explicitly test for it in the body of the function,
1208e.g.::
Georg Brandl116aa622007-08-15 14:28:22 +00001209
1210 def whats_on_the_telly(penguin=None):
1211 if penguin is None:
1212 penguin = []
1213 penguin.append("property of the zoo")
1214 return penguin
1215
Christian Heimesdae2a892008-04-19 00:55:37 +00001216.. index::
Saiyang Gou58d72ca2021-04-07 12:06:43 -07001217 single: / (slash); function definition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001218 single: * (asterisk); function definition
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001219 single: **; function definition
Christian Heimesdae2a892008-04-19 00:55:37 +00001220
1221Function call semantics are described in more detail in section :ref:`calls`. A
Georg Brandl116aa622007-08-15 14:28:22 +00001222function call always assigns values to all parameters mentioned in the parameter
Saiyang Gou58d72ca2021-04-07 12:06:43 -07001223list, either from positional arguments, from keyword arguments, or from default
Georg Brandl116aa622007-08-15 14:28:22 +00001224values. If the form "``*identifier``" is present, it is initialized to a tuple
Eric Snowb957b0c2016-09-08 13:59:58 -07001225receiving any excess positional parameters, defaulting to the empty tuple.
1226If the form "``**identifier``" is present, it is initialized to a new
1227ordered mapping receiving any excess keyword arguments, defaulting to a
1228new empty mapping of the same type. Parameters after "``*``" or
1229"``*identifier``" are keyword-only parameters and may only be passed
Saiyang Gou58d72ca2021-04-07 12:06:43 -07001230by keyword arguments. Parameters before "``/``" are positional-only parameters
1231and may only be passed by positional arguments.
1232
1233.. versionchanged:: 3.8
1234 The ``/`` function parameter syntax may be used to indicate positional-only
1235 parameters. See :pep:`570` for details.
Georg Brandl116aa622007-08-15 14:28:22 +00001236
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001237.. index::
1238 pair: function; annotations
1239 single: ->; function annotations
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001240 single: : (colon); function annotations
Georg Brandl116aa622007-08-15 14:28:22 +00001241
Cheryl Sabellab7105c92018-12-24 00:09:09 -05001242Parameters may have an :term:`annotation <function annotation>` of the form "``: expression``"
1243following the parameter name. Any parameter may have an annotation, even those of the form
Georg Brandl02c30562007-09-07 17:52:53 +00001244``*identifier`` or ``**identifier``. Functions may have "return" annotation of
1245the form "``-> expression``" after the parameter list. These annotations can be
Guido van Rossum95e4d582018-01-26 08:20:18 -08001246any valid Python expression. The presence of annotations does not change the
Batuhan Taskaya044a1042020-10-06 23:03:02 +03001247semantics of a function. The annotation values are available as string values
1248in a dictionary keyed by the parameters' names in the :attr:`__annotations__`
1249attribute of the function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
Georg Brandl242e6a02013-10-06 10:28:39 +02001251.. index:: pair: lambda; expression
Georg Brandl116aa622007-08-15 14:28:22 +00001252
1253It is also possible to create anonymous functions (functions not bound to a
Georg Brandl242e6a02013-10-06 10:28:39 +02001254name), for immediate use in expressions. This uses lambda expressions, described in
1255section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a
Georg Brandl116aa622007-08-15 14:28:22 +00001256simplified function definition; a function defined in a ":keyword:`def`"
1257statement can be passed around or assigned to another name just like a function
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001258defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful
Georg Brandl116aa622007-08-15 14:28:22 +00001259since it allows the execution of multiple statements and annotations.
1260
Georg Brandl242e6a02013-10-06 10:28:39 +02001261**Programmer's note:** Functions are first-class objects. A "``def``" statement
Georg Brandl116aa622007-08-15 14:28:22 +00001262executed inside a function definition defines a local function that can be
1263returned or passed around. Free variables used in the nested function can
1264access the local variables of the function containing the def. See section
1265:ref:`naming` for details.
1266
Georg Brandl64a40942012-03-10 09:22:47 +01001267.. seealso::
1268
1269 :pep:`3107` - Function Annotations
1270 The original specification for function annotations.
1271
Guido van Rossum95e4d582018-01-26 08:20:18 -08001272 :pep:`484` - Type Hints
1273 Definition of a standard meaning for annotations: type hints.
1274
1275 :pep:`526` - Syntax for Variable Annotations
1276 Ability to type hint variable declarations, including class
1277 variables and instance variables
1278
1279 :pep:`563` - Postponed Evaluation of Annotations
1280 Support for forward references within annotations by preserving
1281 annotations in a string form at runtime instead of eager evaluation.
1282
Georg Brandl116aa622007-08-15 14:28:22 +00001283
1284.. _class:
1285
1286Class definitions
1287=================
1288
1289.. index::
Georg Brandl02c30562007-09-07 17:52:53 +00001290 object: class
Christian Heimesfaf2f632008-01-06 16:59:19 +00001291 statement: class
1292 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +00001293 pair: class; name
1294 pair: name; binding
1295 pair: execution; frame
Christian Heimesfaf2f632008-01-06 16:59:19 +00001296 single: inheritance
Georg Brandl3dbca812008-07-23 16:10:53 +00001297 single: docstring
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001298 single: () (parentheses); class definition
1299 single: , (comma); expression list
1300 single: : (colon); compound statement
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl02c30562007-09-07 17:52:53 +00001302A class definition defines a class object (see section :ref:`types`):
1303
Victor Stinner8af239e2020-09-18 09:10:15 +02001304.. productionlist:: python-grammar
Georg Brandl02c30562007-09-07 17:52:53 +00001305 classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite`
Benjamin Peterson54044d62016-05-16 23:20:22 -07001306 inheritance: "(" [`argument_list`] ")"
Georg Brandl02c30562007-09-07 17:52:53 +00001307 classname: `identifier`
1308
Georg Brandl65e5f802010-08-02 18:10:13 +00001309A class definition is an executable statement. The inheritance list usually
1310gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so
1311each item in the list should evaluate to a class object which allows
Éric Araujo28053fb2010-11-22 03:09:19 +00001312subclassing. Classes without an inheritance list inherit, by default, from the
1313base class :class:`object`; hence, ::
1314
1315 class Foo:
1316 pass
1317
1318is equivalent to ::
1319
1320 class Foo(object):
1321 pass
Georg Brandl65e5f802010-08-02 18:10:13 +00001322
1323The class's suite is then executed in a new execution frame (see :ref:`naming`),
1324using a newly created local namespace and the original global namespace.
1325(Usually, the suite contains mostly function definitions.) When the class's
1326suite finishes execution, its execution frame is discarded but its local
1327namespace is saved. [#]_ A class object is then created using the inheritance
1328list for the base classes and the saved local namespace for the attribute
1329dictionary. The class name is bound to this class object in the original local
1330namespace.
1331
Eric Snow92a6c172016-09-05 14:50:11 -07001332The order in which attributes are defined in the class body is preserved
Eric Snow4f29e752016-09-08 15:11:11 -07001333in the new class's ``__dict__``. Note that this is reliable only right
1334after the class is created and only for classes that were defined using
1335the definition syntax.
Eric Snow92a6c172016-09-05 14:50:11 -07001336
Georg Brandl65e5f802010-08-02 18:10:13 +00001337Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`.
Georg Brandl116aa622007-08-15 14:28:22 +00001338
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001339.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001340 single: @ (at); class definition
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001341
Georg Brandlf4142722010-10-17 10:38:20 +00001342Classes can also be decorated: just like when decorating functions, ::
Georg Brandl02c30562007-09-07 17:52:53 +00001343
1344 @f1(arg)
1345 @f2
1346 class Foo: pass
1347
Berker Peksag6cafece2016-08-03 10:17:21 +03001348is roughly equivalent to ::
Georg Brandl02c30562007-09-07 17:52:53 +00001349
1350 class Foo: pass
1351 Foo = f1(arg)(f2(Foo))
1352
Georg Brandlf4142722010-10-17 10:38:20 +00001353The evaluation rules for the decorator expressions are the same as for function
Berker Peksag6cafece2016-08-03 10:17:21 +03001354decorators. The result is then bound to the class name.
Georg Brandlf4142722010-10-17 10:38:20 +00001355
Brandt Bucher8f130532020-03-07 10:23:49 -08001356.. versionchanged:: 3.9
1357 Classes may be decorated with any valid :token:`assignment_expression`.
1358 Previously, the grammar was much more restrictive; see :pep:`614` for
1359 details.
1360
Georg Brandl116aa622007-08-15 14:28:22 +00001361**Programmer's note:** Variables defined in the class definition are class
Georg Brandl65e5f802010-08-02 18:10:13 +00001362attributes; they are shared by instances. Instance attributes can be set in a
1363method with ``self.name = value``. Both class and instance attributes are
1364accessible through the notation "``self.name``", and an instance attribute hides
1365a class attribute with the same name when accessed in this way. Class
1366attributes can be used as defaults for instance attributes, but using mutable
1367values there can lead to unexpected results. :ref:`Descriptors <descriptors>`
1368can be used to create instance variables with different implementation details.
Georg Brandl85eb8c12007-08-31 16:33:38 +00001369
Georg Brandl116aa622007-08-15 14:28:22 +00001370
Georg Brandl02c30562007-09-07 17:52:53 +00001371.. seealso::
1372
Andrés Delfino0f14fc12018-10-19 20:31:15 -03001373 :pep:`3115` - Metaclasses in Python 3000
1374 The proposal that changed the declaration of metaclasses to the current
1375 syntax, and the semantics for how classes with metaclasses are
1376 constructed.
1377
Georg Brandl02c30562007-09-07 17:52:53 +00001378 :pep:`3129` - Class Decorators
Andrés Delfino0f14fc12018-10-19 20:31:15 -03001379 The proposal that added class decorators. Function and method decorators
1380 were introduced in :pep:`318`.
Georg Brandl02c30562007-09-07 17:52:53 +00001381
Georg Brandl02c30562007-09-07 17:52:53 +00001382
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -04001383.. _async:
1384
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001385Coroutines
1386==========
1387
Yury Selivanov5376ba92015-06-22 12:19:30 -04001388.. versionadded:: 3.5
1389
Yury Selivanov66f88282015-06-24 11:04:15 -04001390.. index:: statement: async def
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001391.. _`async def`:
1392
1393Coroutine function definition
1394-----------------------------
1395
Victor Stinner8af239e2020-09-18 09:10:15 +02001396.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001397 async_funcdef: [`decorators`] "async" "def" `funcname` "(" [`parameter_list`] ")"
1398 : ["->" `expression`] ":" `suite`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001399
Yury Selivanov66f88282015-06-24 11:04:15 -04001400.. index::
1401 keyword: async
1402 keyword: await
1403
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001404Execution of Python coroutines can be suspended and resumed at many points
Andre Delfino8adf8d12020-10-12 10:52:30 -03001405(see :term:`coroutine`). :keyword:`await` expressions, :keyword:`async for` and
1406:keyword:`async with` can only be used in the body of a coroutine function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001407
1408Functions defined with ``async def`` syntax are always coroutine functions,
1409even if they do not contain ``await`` or ``async`` keywords.
1410
Andrés Delfino95f68b12018-10-28 07:41:57 -03001411It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the body
1412of a coroutine function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001413
Yury Selivanov5376ba92015-06-22 12:19:30 -04001414An example of a coroutine function::
1415
1416 async def func(param1, param2):
1417 do_stuff()
1418 await some_coroutine()
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001419
Andre Delfino8adf8d12020-10-12 10:52:30 -03001420.. versionchanged:: 3.7
1421 ``await`` and ``async`` are now keywords; previously they were only
1422 treated as such inside the body of a coroutine function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001423
Yury Selivanov66f88282015-06-24 11:04:15 -04001424.. index:: statement: async for
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001425.. _`async for`:
1426
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001427The :keyword:`!async for` statement
1428-----------------------------------
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001429
Victor Stinner8af239e2020-09-18 09:10:15 +02001430.. productionlist:: python-grammar
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001431 async_for_stmt: "async" `for_stmt`
1432
Nick Gaya4b8cdfc2020-12-11 00:27:35 -08001433An :term:`asynchronous iterable` provides an ``__aiter__`` method that directly
1434returns an :term:`asynchronous iterator`, which can call asynchronous code in
1435its ``__anext__`` method.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001436
1437The ``async for`` statement allows convenient iteration over asynchronous
Nick Gaya4b8cdfc2020-12-11 00:27:35 -08001438iterables.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001439
1440The following code::
1441
1442 async for TARGET in ITER:
Géry Ogam226e6e72019-12-30 05:24:51 +00001443 SUITE
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001444 else:
Géry Ogam226e6e72019-12-30 05:24:51 +00001445 SUITE2
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001446
1447Is semantically equivalent to::
1448
1449 iter = (ITER)
Yury Selivanova6f6edb2016-06-09 15:08:31 -04001450 iter = type(iter).__aiter__(iter)
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001451 running = True
Géry Ogam226e6e72019-12-30 05:24:51 +00001452
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001453 while running:
1454 try:
1455 TARGET = await type(iter).__anext__(iter)
1456 except StopAsyncIteration:
1457 running = False
1458 else:
Géry Ogam226e6e72019-12-30 05:24:51 +00001459 SUITE
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001460 else:
Géry Ogam226e6e72019-12-30 05:24:51 +00001461 SUITE2
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001462
1463See also :meth:`__aiter__` and :meth:`__anext__` for details.
1464
Andrés Delfino95f68b12018-10-28 07:41:57 -03001465It is a :exc:`SyntaxError` to use an ``async for`` statement outside the
1466body of a coroutine function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001467
1468
Yury Selivanov66f88282015-06-24 11:04:15 -04001469.. index:: statement: async with
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001470.. _`async with`:
1471
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001472The :keyword:`!async with` statement
1473------------------------------------
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001474
Victor Stinner8af239e2020-09-18 09:10:15 +02001475.. productionlist:: python-grammar
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001476 async_with_stmt: "async" `with_stmt`
1477
1478An :term:`asynchronous context manager` is a :term:`context manager` that is
1479able to suspend execution in its *enter* and *exit* methods.
1480
1481The following code::
1482
Géry Ogam226e6e72019-12-30 05:24:51 +00001483 async with EXPRESSION as TARGET:
1484 SUITE
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001485
Géry Ogam226e6e72019-12-30 05:24:51 +00001486is semantically equivalent to::
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001487
Géry Ogam226e6e72019-12-30 05:24:51 +00001488 manager = (EXPRESSION)
Géry Ogam226e6e72019-12-30 05:24:51 +00001489 aenter = type(manager).__aenter__
Géry Ogam1d1b97a2020-01-14 12:58:29 +01001490 aexit = type(manager).__aexit__
Géry Ogam226e6e72019-12-30 05:24:51 +00001491 value = await aenter(manager)
1492 hit_except = False
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001493
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001494 try:
Géry Ogam226e6e72019-12-30 05:24:51 +00001495 TARGET = value
1496 SUITE
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001497 except:
Géry Ogam226e6e72019-12-30 05:24:51 +00001498 hit_except = True
1499 if not await aexit(manager, *sys.exc_info()):
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001500 raise
Géry Ogam226e6e72019-12-30 05:24:51 +00001501 finally:
1502 if not hit_except:
1503 await aexit(manager, None, None, None)
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001504
1505See also :meth:`__aenter__` and :meth:`__aexit__` for details.
1506
Andrés Delfino95f68b12018-10-28 07:41:57 -03001507It is a :exc:`SyntaxError` to use an ``async with`` statement outside the
1508body of a coroutine function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001509
1510.. seealso::
1511
1512 :pep:`492` - Coroutines with async and await syntax
Andrés Delfino0f14fc12018-10-19 20:31:15 -03001513 The proposal that made coroutines a proper standalone concept in Python,
1514 and added supporting syntax.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001515
1516
Georg Brandl116aa622007-08-15 14:28:22 +00001517.. rubric:: Footnotes
1518
Ezio Melottifc3db8a2011-06-26 11:25:28 +03001519.. [#] The exception is propagated to the invocation stack unless
1520 there is a :keyword:`finally` clause which happens to raise another
1521 exception. That new exception causes the old one to be lost.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
Georg Brandl3dbca812008-07-23 16:10:53 +00001523.. [#] A string literal appearing as the first statement in the function body is
1524 transformed into the function's ``__doc__`` attribute and therefore the
1525 function's :term:`docstring`.
1526
1527.. [#] A string literal appearing as the first statement in the class body is
1528 transformed into the namespace's ``__doc__`` item and therefore the class's
1529 :term:`docstring`.