blob: 6aafa7258f1690f731550fa02bd29e9eded617e9 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _simple:
3
4*****************
5Simple statements
6*****************
7
8.. index:: pair: simple; statement
9
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070010A simple statement is comprised within a single logical line. Several simple
Georg Brandl116aa622007-08-15 14:28:22 +000011statements may occur on a single line separated by semicolons. The syntax for
12simple statements is:
13
14.. productionlist::
15 simple_stmt: `expression_stmt`
16 : | `assert_stmt`
17 : | `assignment_stmt`
18 : | `augmented_assignment_stmt`
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070019 : | `annotated_assignment_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000020 : | `pass_stmt`
21 : | `del_stmt`
22 : | `return_stmt`
23 : | `yield_stmt`
24 : | `raise_stmt`
25 : | `break_stmt`
26 : | `continue_stmt`
27 : | `import_stmt`
28 : | `global_stmt`
Georg Brandl02c30562007-09-07 17:52:53 +000029 : | `nonlocal_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000030
31
32.. _exprstmts:
33
34Expression statements
35=====================
36
Christian Heimesfaf2f632008-01-06 16:59:19 +000037.. index::
38 pair: expression; statement
39 pair: expression; list
Georg Brandl02c30562007-09-07 17:52:53 +000040.. index:: pair: expression; list
Georg Brandl116aa622007-08-15 14:28:22 +000041
42Expression statements are used (mostly interactively) to compute and write a
43value, or (usually) to call a procedure (a function that returns no meaningful
44result; in Python, procedures return the value ``None``). Other uses of
45expression statements are allowed and occasionally useful. The syntax for an
46expression statement is:
47
48.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000049 expression_stmt: `starred_expression`
Georg Brandl116aa622007-08-15 14:28:22 +000050
Georg Brandl116aa622007-08-15 14:28:22 +000051An expression statement evaluates the expression list (which may be a single
52expression).
53
54.. index::
55 builtin: repr
56 object: None
57 pair: string; conversion
58 single: output
59 pair: standard; output
60 pair: writing; values
61 pair: procedure; call
62
63In interactive mode, if the value is not ``None``, it is converted to a string
64using the built-in :func:`repr` function and the resulting string is written to
Georg Brandl02c30562007-09-07 17:52:53 +000065standard output on a line by itself (except if the result is ``None``, so that
66procedure calls do not cause any output.)
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068.. _assignment:
69
70Assignment statements
71=====================
72
73.. index::
Terry Jan Reedy9cc90262014-04-29 01:19:17 -040074 single: =; assignment statement
Georg Brandl116aa622007-08-15 14:28:22 +000075 pair: assignment; statement
76 pair: binding; name
77 pair: rebinding; name
78 object: mutable
79 pair: attribute; assignment
80
81Assignment statements are used to (re)bind names to values and to modify
82attributes or items of mutable objects:
83
84.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000085 assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`)
Georg Brandl116aa622007-08-15 14:28:22 +000086 target_list: `target` ("," `target`)* [","]
87 target: `identifier`
Berker Peksag094c9c92016-05-18 08:44:29 +030088 : | "(" [`target_list`] ")"
89 : | "[" [`target_list`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +000090 : | `attributeref`
91 : | `subscription`
92 : | `slicing`
Georg Brandl02c30562007-09-07 17:52:53 +000093 : | "*" `target`
Georg Brandl116aa622007-08-15 14:28:22 +000094
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070095(See section :ref:`primaries` for the syntax definitions for *attributeref*,
96*subscription*, and *slicing*.)
Georg Brandl116aa622007-08-15 14:28:22 +000097
Georg Brandl116aa622007-08-15 14:28:22 +000098An assignment statement evaluates the expression list (remember that this can be
99a single expression or a comma-separated list, the latter yielding a tuple) and
100assigns the single resulting object to each of the target lists, from left to
101right.
102
103.. index::
104 single: target
105 pair: target; list
106
107Assignment is defined recursively depending on the form of the target (list).
108When a target is part of a mutable object (an attribute reference, subscription
109or slicing), the mutable object must ultimately perform the assignment and
110decide about its validity, and may raise an exception if the assignment is
111unacceptable. The rules observed by various types and the exceptions raised are
112given with the definition of the object types (see section :ref:`types`).
113
114.. index:: triple: target; list; assignment
115
Georg Brandl02c30562007-09-07 17:52:53 +0000116Assignment of an object to a target list, optionally enclosed in parentheses or
117square brackets, is recursively defined as follows.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Berker Peksag094c9c92016-05-18 08:44:29 +0300119* If the target list is empty: The object must also be an empty iterable.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Berker Peksag094c9c92016-05-18 08:44:29 +0300121* If the target list is a single target in parentheses: The object is assigned
122 to that target.
123
124* If the target list is a comma-separated list of targets, or a single target
125 in square brackets: The object must be an iterable with the same number of
126 items as there are targets in the target list, and the items are assigned,
127 from left to right, to the corresponding targets.
Georg Brandl02c30562007-09-07 17:52:53 +0000128
129 * If the target list contains one target prefixed with an asterisk, called a
Berker Peksag094c9c92016-05-18 08:44:29 +0300130 "starred" target: The object must be an iterable with at least as many items
Georg Brandl02c30562007-09-07 17:52:53 +0000131 as there are targets in the target list, minus one. The first items of the
Berker Peksag094c9c92016-05-18 08:44:29 +0300132 iterable are assigned, from left to right, to the targets before the starred
133 target. The final items of the iterable are assigned to the targets after
134 the starred target. A list of the remaining items in the iterable is then
Georg Brandl02c30562007-09-07 17:52:53 +0000135 assigned to the starred target (the list can be empty).
136
Berker Peksag094c9c92016-05-18 08:44:29 +0300137 * Else: The object must be an iterable with the same number of items as there
Georg Brandl02c30562007-09-07 17:52:53 +0000138 are targets in the target list, and the items are assigned, from left to
139 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141Assignment of an object to a single target is recursively defined as follows.
142
143* If the target is an identifier (name):
144
Georg Brandl02c30562007-09-07 17:52:53 +0000145 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
146 statement in the current code block: the name is bound to the object in the
147 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Georg Brandl02c30562007-09-07 17:52:53 +0000149 * Otherwise: the name is bound to the object in the global namespace or the
150 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Georg Brandl482b1512010-03-21 09:02:59 +0000152 .. index:: single: destructor
153
Georg Brandl02c30562007-09-07 17:52:53 +0000154 The name is rebound if it was already bound. This may cause the reference
155 count for the object previously bound to the name to reach zero, causing the
156 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000158 .. index:: pair: attribute; assignment
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160* If the target is an attribute reference: The primary expression in the
161 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000162 if this is not the case, :exc:`TypeError` is raised. That object is then
163 asked to assign the assigned object to the given attribute; if it cannot
164 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000165 :exc:`AttributeError`).
166
Georg Brandlee8783d2009-09-16 16:00:31 +0000167 .. _attr-target-note:
168
169 Note: If the object is a class instance and the attribute reference occurs on
170 both sides of the assignment operator, the RHS expression, ``a.x`` can access
171 either an instance attribute or (if no instance attribute exists) a class
172 attribute. The LHS target ``a.x`` is always set as an instance attribute,
173 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
174 necessarily refer to the same attribute: if the RHS expression refers to a
175 class attribute, the LHS creates a new instance attribute as the target of the
176 assignment::
177
178 class Cls:
179 x = 3 # class variable
180 inst = Cls()
181 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
182
183 This description does not necessarily apply to descriptor attributes, such as
184 properties created with :func:`property`.
185
Georg Brandl116aa622007-08-15 14:28:22 +0000186 .. index::
187 pair: subscription; assignment
188 object: mutable
189
190* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000191 evaluated. It should yield either a mutable sequence object (such as a list)
192 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000193 evaluated.
194
195 .. index::
196 object: sequence
197 object: list
198
Georg Brandl02c30562007-09-07 17:52:53 +0000199 If the primary is a mutable sequence object (such as a list), the subscript
200 must yield an integer. If it is negative, the sequence's length is added to
201 it. The resulting value must be a nonnegative integer less than the
202 sequence's length, and the sequence is asked to assign the assigned object to
203 its item with that index. If the index is out of range, :exc:`IndexError` is
204 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206 .. index::
207 object: mapping
208 object: dictionary
209
210 If the primary is a mapping object (such as a dictionary), the subscript must
211 have a type compatible with the mapping's key type, and the mapping is then
212 asked to create a key/datum pair which maps the subscript to the assigned
213 object. This can either replace an existing key/value pair with the same key
214 value, or insert a new key/value pair (if no key with the same value existed).
215
Georg Brandl02c30562007-09-07 17:52:53 +0000216 For user-defined objects, the :meth:`__setitem__` method is called with
217 appropriate arguments.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219 .. index:: pair: slicing; assignment
220
221* If the target is a slicing: The primary expression in the reference is
222 evaluated. It should yield a mutable sequence object (such as a list). The
223 assigned object should be a sequence object of the same type. Next, the lower
224 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000225 are zero and the sequence's length. The bounds should evaluate to integers.
226 If either bound is negative, the sequence's length is added to it. The
227 resulting bounds are clipped to lie between zero and the sequence's length,
228 inclusive. Finally, the sequence object is asked to replace the slice with
229 the items of the assigned sequence. The length of the slice may be different
230 from the length of the assigned sequence, thus changing the length of the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700231 target sequence, if the target sequence allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Georg Brandl495f7b52009-10-27 15:28:25 +0000233.. impl-detail::
234
235 In the current implementation, the syntax for targets is taken to be the same
236 as for expressions, and invalid syntax is rejected during the code generation
237 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700239Although the definition of assignment implies that overlaps between the
Martin Panterf05641642016-05-08 13:48:10 +0000240left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700241b, a`` swaps two variables), overlaps *within* the collection of assigned-to
242variables occur left-to-right, sometimes resulting in confusion. For instance,
243the following program prints ``[0, 2]``::
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 x = [0, 1]
246 i = 0
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700247 i, x[i] = 1, 2 # i is updated, then x[i] is updated
Georg Brandl6911e3c2007-09-04 07:15:32 +0000248 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250
Georg Brandl02c30562007-09-07 17:52:53 +0000251.. seealso::
252
253 :pep:`3132` - Extended Iterable Unpacking
254 The specification for the ``*target`` feature.
255
256
Georg Brandl116aa622007-08-15 14:28:22 +0000257.. _augassign:
258
259Augmented assignment statements
260-------------------------------
261
262.. index::
263 pair: augmented; assignment
264 single: statement; assignment, augmented
Terry Jan Reedy9cc90262014-04-29 01:19:17 -0400265 single: +=; augmented assignment
266 single: -=; augmented assignment
267 single: *=; augmented assignment
268 single: /=; augmented assignment
269 single: %=; augmented assignment
270 single: &=; augmented assignment
271 single: ^=; augmented assignment
272 single: |=; augmented assignment
273 single: **=; augmented assignment
274 single: //=; augmented assignment
275 single: >>=; augmented assignment
276 single: <<=; augmented assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278Augmented assignment is the combination, in a single statement, of a binary
279operation and an assignment statement:
280
281.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000282 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
283 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Petersond51374e2014-04-09 23:55:56 -0400284 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000285 : | ">>=" | "<<=" | "&=" | "^=" | "|="
286
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700287(See section :ref:`primaries` for the syntax definitions of the last three
Georg Brandl116aa622007-08-15 14:28:22 +0000288symbols.)
289
290An augmented assignment evaluates the target (which, unlike normal assignment
291statements, cannot be an unpacking) and the expression list, performs the binary
292operation specific to the type of assignment on the two operands, and assigns
293the result to the original target. The target is only evaluated once.
294
295An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2961`` to achieve a similar, but not exactly equal effect. In the augmented
297version, ``x`` is only evaluated once. Also, when possible, the actual operation
298is performed *in-place*, meaning that rather than creating a new object and
299assigning that to the target, the old object is modified instead.
300
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700301Unlike normal assignments, augmented assignments evaluate the left-hand side
302*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
303looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
304lastly, it writes the result back to ``a[i]``.
305
Georg Brandl116aa622007-08-15 14:28:22 +0000306With the exception of assigning to tuples and multiple targets in a single
307statement, the assignment done by augmented assignment statements is handled the
308same way as normal assignments. Similarly, with the exception of the possible
309*in-place* behavior, the binary operation performed by augmented assignment is
310the same as the normal binary operations.
311
Georg Brandlee8783d2009-09-16 16:00:31 +0000312For targets which are attribute references, the same :ref:`caveat about class
313and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700316.. _annassign:
317
318Annotated assignment statements
319-------------------------------
320
321.. index::
322 pair: annotated; assignment
323 single: statement; assignment, annotated
324
325Annotation assignment is the combination, in a single statement,
326of a variable or attribute annotation and an optional assignment statement:
327
328.. productionlist::
329 annotated_assignment_stmt: `augtarget` ":" `expression` ["=" `expression`]
330
331The difference from normal :ref:`assignment` is that only single target and
332only single right hand side value is allowed.
333
334For simple names as assignment targets, if in class or module scope,
335the annotations are evaluated and stored in a special class or module
336attribute :attr:`__annotations__`
337that is a dictionary mapping from variable names to evaluated annotations.
338This attribute is writable and is automatically created at the start
339of class or module body execution, if annotations are found statically.
340
341For expressions as assignment targets, the annotations are evaluated if
342in class or module scope, but not stored.
343
344If a name is annotated in a function scope, then this name is local for
345that scope. Annotations are never evaluated and stored in function scopes.
346
347If the right hand side is present, an annotated
348assignment performs the actual assignment before evaluating annotations
349(where applicable). If the right hand side is not present for an expression
350target, then the interpreter evaluates the target except for the last
351:meth:`__setitem__` or :meth:`__setattr__` call.
352
353.. seealso::
354
355 :pep:`526` - Variable and attribute annotation syntax
356 :pep:`484` - Type hints
357
358
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000359.. _assert:
360
361The :keyword:`assert` statement
362===============================
363
364.. index::
365 statement: assert
366 pair: debugging; assertions
367
368Assert statements are a convenient way to insert debugging assertions into a
369program:
370
371.. productionlist::
372 assert_stmt: "assert" `expression` ["," `expression`]
373
374The simple form, ``assert expression``, is equivalent to ::
375
376 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300377 if not expression: raise AssertionError
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000378
379The extended form, ``assert expression1, expression2``, is equivalent to ::
380
381 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300382 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383
384.. index::
385 single: __debug__
386 exception: AssertionError
387
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000388These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000390built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000391``False`` when optimization is requested (command line option -O). The current
392code generator emits no code for an assert statement when optimization is
393requested at compile time. Note that it is unnecessary to include the source
394code for the expression that failed in the error message; it will be displayed
395as part of the stack trace.
396
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000397Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398is determined when the interpreter starts.
399
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401.. _pass:
402
403The :keyword:`pass` statement
404=============================
405
Christian Heimesfaf2f632008-01-06 16:59:19 +0000406.. index::
407 statement: pass
408 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000409 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411.. productionlist::
412 pass_stmt: "pass"
413
Georg Brandl116aa622007-08-15 14:28:22 +0000414:keyword:`pass` is a null operation --- when it is executed, nothing happens.
415It is useful as a placeholder when a statement is required syntactically, but no
416code needs to be executed, for example::
417
418 def f(arg): pass # a function that does nothing (yet)
419
420 class C: pass # a class with no methods (yet)
421
422
423.. _del:
424
425The :keyword:`del` statement
426============================
427
Christian Heimesfaf2f632008-01-06 16:59:19 +0000428.. index::
429 statement: del
430 pair: deletion; target
431 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433.. productionlist::
434 del_stmt: "del" `target_list`
435
Georg Brandl116aa622007-08-15 14:28:22 +0000436Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100437Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439Deletion of a target list recursively deletes each target, from left to right.
440
441.. index::
442 statement: global
443 pair: unbinding; name
444
Georg Brandl02c30562007-09-07 17:52:53 +0000445Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000446namespace, depending on whether the name occurs in a :keyword:`global` statement
447in the same code block. If the name is unbound, a :exc:`NameError` exception
448will be raised.
449
Georg Brandl116aa622007-08-15 14:28:22 +0000450.. index:: pair: attribute; deletion
451
452Deletion of attribute references, subscriptions and slicings is passed to the
453primary object involved; deletion of a slicing is in general equivalent to
454assignment of an empty slice of the right type (but even this is determined by
455the sliced object).
456
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000457.. versionchanged:: 3.2
458 Previously it was illegal to delete a name from the local namespace if it
459 occurs as a free variable in a nested block.
460
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462.. _return:
463
464The :keyword:`return` statement
465===============================
466
Christian Heimesfaf2f632008-01-06 16:59:19 +0000467.. index::
468 statement: return
469 pair: function; definition
470 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472.. productionlist::
473 return_stmt: "return" [`expression_list`]
474
Georg Brandl116aa622007-08-15 14:28:22 +0000475:keyword:`return` may only occur syntactically nested in a function definition,
476not within a nested class definition.
477
478If an expression list is present, it is evaluated, else ``None`` is substituted.
479
480:keyword:`return` leaves the current function call with the expression list (or
481``None``) as return value.
482
483.. index:: keyword: finally
484
485When :keyword:`return` passes control out of a :keyword:`try` statement with a
486:keyword:`finally` clause, that :keyword:`finally` clause is executed before
487really leaving the function.
488
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000489In a generator function, the :keyword:`return` statement indicates that the
490generator is done and will cause :exc:`StopIteration` to be raised. The returned
491value (if any) is used as an argument to construct :exc:`StopIteration` and
492becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494
495.. _yield:
496
497The :keyword:`yield` statement
498==============================
499
Christian Heimesfaf2f632008-01-06 16:59:19 +0000500.. index::
501 statement: yield
502 single: generator; function
503 single: generator; iterator
504 single: function; generator
505 exception: StopIteration
506
Georg Brandl116aa622007-08-15 14:28:22 +0000507.. productionlist::
508 yield_stmt: `yield_expression`
509
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500510A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
511expression <yieldexpr>`. The yield statement can be used to omit the parentheses
512that would otherwise be required in the equivalent yield expression
513statement. For example, the yield statements ::
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000514
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500515 yield <expr>
516 yield from <expr>
Christian Heimes33fe8092008-04-13 13:53:33 +0000517
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500518are equivalent to the yield expression statements ::
Christian Heimes33fe8092008-04-13 13:53:33 +0000519
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500520 (yield <expr>)
521 (yield from <expr>)
Christian Heimes33fe8092008-04-13 13:53:33 +0000522
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500523Yield expressions and statements are only used when defining a :term:`generator`
524function, and are only used in the body of the generator function. Using yield
525in a function definition is sufficient to cause that definition to create a
526generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000527
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500528For full details of :keyword:`yield` semantics, refer to the
529:ref:`yieldexpr` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531.. _raise:
532
533The :keyword:`raise` statement
534==============================
535
Christian Heimesfaf2f632008-01-06 16:59:19 +0000536.. index::
537 statement: raise
538 single: exception
539 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000540 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000543 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545If no expressions are present, :keyword:`raise` re-raises the last exception
546that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100547scope, a :exc:`RuntimeError` exception is raised indicating that this is an
548error.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
Georg Brandl02c30562007-09-07 17:52:53 +0000550Otherwise, :keyword:`raise` evaluates the first expression as the exception
551object. It must be either a subclass or an instance of :class:`BaseException`.
552If it is a class, the exception instance will be obtained when needed by
553instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Georg Brandl02c30562007-09-07 17:52:53 +0000555The :dfn:`type` of the exception is the exception instance's class, the
556:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558.. index:: object: traceback
559
Georg Brandl02c30562007-09-07 17:52:53 +0000560A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000561and attached to it as the :attr:`__traceback__` attribute, which is writable.
562You can create an exception and set your own traceback in one step using the
563:meth:`with_traceback` exception method (which returns the same exception
564instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000565
Benjamin Petersonb7851692009-02-16 16:15:34 +0000566 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000567
Georg Brandl1aea30a2008-07-19 15:51:07 +0000568.. index:: pair: exception; chaining
569 __cause__ (exception attribute)
570 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000571
Georg Brandl1aea30a2008-07-19 15:51:07 +0000572The ``from`` clause is used for exception chaining: if given, the second
573*expression* must be another exception class or instance, which will then be
574attached to the raised exception as the :attr:`__cause__` attribute (which is
575writable). If the raised exception is not handled, both exceptions will be
576printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000577
Georg Brandl1aea30a2008-07-19 15:51:07 +0000578 >>> try:
579 ... print(1 / 0)
580 ... except Exception as exc:
581 ... raise RuntimeError("Something bad happened") from exc
582 ...
583 Traceback (most recent call last):
584 File "<stdin>", line 2, in <module>
585 ZeroDivisionError: int division or modulo by zero
586
587 The above exception was the direct cause of the following exception:
588
589 Traceback (most recent call last):
590 File "<stdin>", line 4, in <module>
591 RuntimeError: Something bad happened
592
593A similar mechanism works implicitly if an exception is raised inside an
Georg Brandla4c8c472014-10-31 10:38:49 +0100594exception handler or a :keyword:`finally` clause: the previous exception is then
595attached as the new exception's :attr:`__context__` attribute::
Georg Brandl1aea30a2008-07-19 15:51:07 +0000596
597 >>> try:
598 ... print(1 / 0)
599 ... except:
600 ... raise RuntimeError("Something bad happened")
601 ...
602 Traceback (most recent call last):
603 File "<stdin>", line 2, in <module>
604 ZeroDivisionError: int division or modulo by zero
605
606 During handling of the above exception, another exception occurred:
607
608 Traceback (most recent call last):
609 File "<stdin>", line 4, in <module>
610 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000611
612Additional information on exceptions can be found in section :ref:`exceptions`,
613and information about handling exceptions is in section :ref:`try`.
614
615
616.. _break:
617
618The :keyword:`break` statement
619==============================
620
Christian Heimesfaf2f632008-01-06 16:59:19 +0000621.. index::
622 statement: break
623 statement: for
624 statement: while
625 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627.. productionlist::
628 break_stmt: "break"
629
Georg Brandl116aa622007-08-15 14:28:22 +0000630:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
631:keyword:`while` loop, but not nested in a function or class definition within
632that loop.
633
634.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000635 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000636
637It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
638clause if the loop has one.
639
Georg Brandl116aa622007-08-15 14:28:22 +0000640If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
641target keeps its current value.
642
643.. index:: keyword: finally
644
645When :keyword:`break` passes control out of a :keyword:`try` statement with a
646:keyword:`finally` clause, that :keyword:`finally` clause is executed before
647really leaving the loop.
648
649
650.. _continue:
651
652The :keyword:`continue` statement
653=================================
654
Christian Heimesfaf2f632008-01-06 16:59:19 +0000655.. index::
656 statement: continue
657 statement: for
658 statement: while
659 pair: loop; statement
660 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000661
662.. productionlist::
663 continue_stmt: "continue"
664
Georg Brandl116aa622007-08-15 14:28:22 +0000665:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
666:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000667:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000668cycle of the nearest enclosing loop.
669
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000670When :keyword:`continue` passes control out of a :keyword:`try` statement with a
671:keyword:`finally` clause, that :keyword:`finally` clause is executed before
672really starting the next loop cycle.
673
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000676.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678The :keyword:`import` statement
679===============================
680
681.. index::
682 statement: import
683 single: module; importing
684 pair: name; binding
685 keyword: from
686
687.. productionlist::
688 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
689 : | "from" `relative_module` "import" `identifier` ["as" `name`]
690 : ( "," `identifier` ["as" `name`] )*
691 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
692 : ( "," `identifier` ["as" `name`] )* [","] ")"
693 : | "from" `module` "import" "*"
694 module: (`identifier` ".")* `identifier`
695 relative_module: "."* `module` | "."+
696 name: `identifier`
697
Nick Coghlane3376ef2012-08-02 22:02:35 +1000698The basic import statement (no :keyword:`from` clause) is executed in two
699steps:
Barry Warsawdadebab2012-07-31 16:03:09 -0400700
Nick Coghlane3376ef2012-08-02 22:02:35 +1000701#. find a module, loading and initializing it if necessary
702#. define a name or names in the local namespace for the scope where
703 the :keyword:`import` statement occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Nick Coghlane3376ef2012-08-02 22:02:35 +1000705When the statement contains multiple clauses (separated by
706commas) the two steps are carried out separately for each clause, just
Ned Deilycec95812016-05-17 21:44:46 -0400707as though the clauses had been separated out into individual import
Nick Coghlane3376ef2012-08-02 22:02:35 +1000708statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700710The details of the first step, finding and loading modules are described in
Nick Coghlane3376ef2012-08-02 22:02:35 +1000711greater detail in the section on the :ref:`import system <importsystem>`,
712which also describes the various types of packages and modules that can
713be imported, as well as all the hooks that can be used to customize
714the import system. Note that failures in this step may indicate either
715that the module could not be located, *or* that an error occurred while
716initializing the module, which includes execution of the module's code.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Nick Coghlane3376ef2012-08-02 22:02:35 +1000718If the requested module is retrieved successfully, it will be made
719available in the local namespace in one of three ways:
720
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400721.. index:: single: as; import statement
722
Nick Coghlane3376ef2012-08-02 22:02:35 +1000723* If the module name is followed by :keyword:`as`, then the name
724 following :keyword:`as` is bound directly to the imported module.
725* If no other name is specified, and the module being imported is a top
726 level module, the module's name is bound in the local namespace as a
727 reference to the imported module
728* If the module being imported is *not* a top level module, then the name
729 of the top level package that contains the module is bound in the local
730 namespace as a reference to the top level package. The imported module
731 must be accessed using its full qualified name rather than directly
732
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734.. index::
735 pair: name; binding
Nick Coghlane3376ef2012-08-02 22:02:35 +1000736 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000737 exception: ImportError
738
Nick Coghlane3376ef2012-08-02 22:02:35 +1000739The :keyword:`from` form uses a slightly more complex process:
740
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700741#. find the module specified in the :keyword:`from` clause, loading and
Nick Coghlane3376ef2012-08-02 22:02:35 +1000742 initializing it if necessary;
743#. for each of the identifiers specified in the :keyword:`import` clauses:
744
745 #. check if the imported module has an attribute by that name
746 #. if not, attempt to import a submodule with that name and then
747 check the imported module again for that attribute
748 #. if the attribute is not found, :exc:`ImportError` is raised.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700749 #. otherwise, a reference to that value is stored in the local namespace,
Nick Coghlane3376ef2012-08-02 22:02:35 +1000750 using the name in the :keyword:`as` clause if it is present,
751 otherwise using the attribute name
752
753Examples::
754
755 import foo # foo imported and bound locally
756 import foo.bar.baz # foo.bar.baz imported, foo bound locally
757 import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
758 from foo.bar import baz # foo.bar.baz imported and bound as baz
759 from foo import attr # foo imported and foo.attr bound as attr
760
761If the list of identifiers is replaced by a star (``'*'``), all public
762names defined in the module are bound in the local namespace for the scope
763where the :keyword:`import` statement occurs.
764
765.. index:: single: __all__ (optional module attribute)
766
767The *public names* defined by a module are determined by checking the module's
768namespace for a variable named ``__all__``; if defined, it must be a sequence
769of strings which are names defined or imported by that module. The names
770given in ``__all__`` are all considered public and are required to exist. If
771``__all__`` is not defined, the set of public names includes all names found
772in the module's namespace which do not begin with an underscore character
773(``'_'``). ``__all__`` should contain the entire public API. It is intended
774to avoid accidentally exporting items that are not part of the API (such as
775library modules which were imported and used within the module).
776
Georg Brandla4c8c472014-10-31 10:38:49 +0100777The wild card form of import --- ``from module import *`` --- is only allowed at
778the module level. Attempting to use it in class or function definitions will
779raise a :exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000782 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Brett Cannone43b0602009-03-21 03:11:16 +0000784When specifying what module to import you do not have to specify the absolute
785name of the module. When a module or package is contained within another
786package it is possible to make a relative import within the same top package
787without having to mention the package name. By using leading dots in the
788specified module or package after :keyword:`from` you can specify how high to
789traverse up the current package hierarchy without specifying exact names. One
790leading dot means the current package where the module making the import
791exists. Two dots means up one package level. Three dots is up two levels, etc.
792So if you execute ``from . import mod`` from a module in the ``pkg`` package
793then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000794import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Brett Cannone43b0602009-03-21 03:11:16 +0000795The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000796
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000797:func:`importlib.import_module` is provided to support applications that
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700798determine dynamically the modules to be loaded.
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800
801.. _future:
802
803Future statements
804-----------------
805
806.. index:: pair: future; statement
807
808A :dfn:`future statement` is a directive to the compiler that a particular
809module should be compiled using syntax or semantics that will be available in a
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700810specified future release of Python where the feature becomes standard.
811
812The future statement is intended to ease migration to future versions of Python
813that introduce incompatible changes to the language. It allows use of the new
814features on a per-module basis before the release in which the feature becomes
815standard.
Georg Brandl116aa622007-08-15 14:28:22 +0000816
817.. productionlist:: *
818 future_statement: "from" "__future__" "import" feature ["as" name]
819 : ("," feature ["as" name])*
820 : | "from" "__future__" "import" "(" feature ["as" name]
821 : ("," feature ["as" name])* [","] ")"
822 feature: identifier
823 name: identifier
824
825A future statement must appear near the top of the module. The only lines that
826can appear before a future statement are:
827
828* the module docstring (if any),
829* comments,
830* blank lines, and
831* other future statements.
832
Georg Brandl02c30562007-09-07 17:52:53 +0000833.. XXX change this if future is cleaned out
834
835The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000836``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
837``with_statement``. They are all redundant because they are always enabled, and
838only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840A future statement is recognized and treated specially at compile time: Changes
841to the semantics of core constructs are often implemented by generating
842different code. It may even be the case that a new feature introduces new
843incompatible syntax (such as a new reserved word), in which case the compiler
844may need to parse the module differently. Such decisions cannot be pushed off
845until runtime.
846
847For any given release, the compiler knows which feature names have been defined,
848and raises a compile-time error if a future statement contains a feature not
849known to it.
850
851The direct runtime semantics are the same as for any import statement: there is
852a standard module :mod:`__future__`, described later, and it will be imported in
853the usual way at the time the future statement is executed.
854
855The interesting runtime semantics depend on the specific feature enabled by the
856future statement.
857
858Note that there is nothing special about the statement::
859
860 import __future__ [as name]
861
862That is not a future statement; it's an ordinary import statement with no
863special semantics or syntax restrictions.
864
Georg Brandl22b34312009-07-26 14:54:51 +0000865Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000866that occur in a module :mod:`M` containing a future statement will, by default,
867use the new syntax or semantics associated with the future statement. This can
868be controlled by optional arguments to :func:`compile` --- see the documentation
869of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871A future statement typed at an interactive interpreter prompt will take effect
872for the rest of the interpreter session. If an interpreter is started with the
873:option:`-i` option, is passed a script name to execute, and the script includes
874a future statement, it will be in effect in the interactive session started
875after the script is executed.
876
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000877.. seealso::
878
879 :pep:`236` - Back to the __future__
880 The original proposal for the __future__ mechanism.
881
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883.. _global:
884
885The :keyword:`global` statement
886===============================
887
Christian Heimesfaf2f632008-01-06 16:59:19 +0000888.. index::
889 statement: global
890 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000891
892.. productionlist::
893 global_stmt: "global" `identifier` ("," `identifier`)*
894
Georg Brandl116aa622007-08-15 14:28:22 +0000895The :keyword:`global` statement is a declaration which holds for the entire
896current code block. It means that the listed identifiers are to be interpreted
897as globals. It would be impossible to assign to a global variable without
898:keyword:`global`, although free variables may refer to globals without being
899declared global.
900
901Names listed in a :keyword:`global` statement must not be used in the same code
902block textually preceding that :keyword:`global` statement.
903
904Names listed in a :keyword:`global` statement must not be defined as formal
905parameters or in a :keyword:`for` loop control target, :keyword:`class`
Guido van Rossum6cff8742016-09-09 09:36:26 -0700906definition, function definition, :keyword:`import` statement, or variable
907annotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
Georg Brandl495f7b52009-10-27 15:28:25 +0000909.. impl-detail::
910
Guido van Rossum6cff8742016-09-09 09:36:26 -0700911 The current implementation does not enforce some of these restriction, but
Georg Brandl495f7b52009-10-27 15:28:25 +0000912 programs should not abuse this freedom, as future implementations may enforce
913 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915.. index::
916 builtin: exec
917 builtin: eval
918 builtin: compile
919
920**Programmer's note:** the :keyword:`global` is a directive to the parser. It
921applies only to code parsed at the same time as the :keyword:`global` statement.
922In particular, a :keyword:`global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000923object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000924block *containing* the function call, and code contained in such a string is
925unaffected by :keyword:`global` statements in the code containing the function
926call. The same applies to the :func:`eval` and :func:`compile` functions.
927
Georg Brandl02c30562007-09-07 17:52:53 +0000928
929.. _nonlocal:
930
931The :keyword:`nonlocal` statement
932=================================
933
934.. index:: statement: nonlocal
935
936.. productionlist::
937 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
938
Georg Brandlc5d98b42007-12-04 18:11:03 +0000939.. XXX add when implemented
Martin Panter0c0da482016-06-12 01:46:50 +0000940 : ["=" (`target_list` "=")+ starred_expression]
Georg Brandl06788c92009-01-03 21:31:47 +0000941 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000942
Georg Brandl48310cd2009-01-03 21:18:54 +0000943The :keyword:`nonlocal` statement causes the listed identifiers to refer to
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700944previously bound variables in the nearest enclosing scope excluding globals.
945This is important because the default behavior for binding is to search the
946local namespace first. The statement allows encapsulated code to rebind
947variables outside of the local scope besides the global (module) scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +0000948
Georg Brandlc5d98b42007-12-04 18:11:03 +0000949.. XXX not implemented
950 The :keyword:`nonlocal` statement may prepend an assignment or augmented
951 assignment, but not an expression.
952
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700953Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
Georg Brandlc5d98b42007-12-04 18:11:03 +0000954:keyword:`global` statement, must refer to pre-existing bindings in an
955enclosing scope (the scope in which a new binding should be created cannot
956be determined unambiguously).
957
Georg Brandl48310cd2009-01-03 21:18:54 +0000958Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +0000959pre-existing bindings in the local scope.
960
961.. seealso::
962
963 :pep:`3104` - Access to Names in Outer Scopes
964 The specification for the :keyword:`nonlocal` statement.