Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:
assignment_stmt | ::= | (target_list "=")+ (expression_list | yield_expression) |
target_list | ::= | target ("," target)* [","] |
target | ::= | identifier |
| "(" target_list ")" | ||
| "[" target_list "]" | ||
| attributeref | ||
| subscription | ||
| slicing |
(See section 5.3 for the syntax definitions for the last three symbols.)
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section 3.2).
Assignment of an object to a target list is recursively defined as follows.
Assignment of an object to a single target is recursively defined as follows.
The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.
If the primary is a mutable sequence object (such as a list), the subscript must yield a plain integer. If it is negative, the sequence's length is added to it. The resulting value must be a nonnegative integer less than the sequence's length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).
If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping's key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).
(In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.)
WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (for example "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]":
x = [0, 1] i = 0 i, x[i] = 1, 2 print x