Reputation: 38960
I came across this piece of code and am wondering what it means:
typ, dat = imap_conn.search(None, search_string)
What exactly does the typ, dat
part of the line mean?
Upvotes: 0
Views: 484
Reputation: 39709
typ, dat = imap_conn.search(None, search_string)
The expression on right-hand side returns two values which are assigned to the two variables on the left-hand side.
Upvotes: 0
Reputation: 95742
The syntax for assignments is given at http://docs.python.org/reference/simple_stmts.html#assignment-statements
assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
target_list ::= target ("," target)* [","]
target ::= identifier
| "(" target_list ")"
| "[" target_list "]"
| attributeref
| subscription
| slicing
the left hand side of the assignment contains one or more target_list
which are comma separate targets. A sequence on the right hand side is then unpacked into each target. Notice that the definition is recursive, so you can even do things like:
a, [b, c, [d, e]], f = 1, (2, 3, (4, 5)), 6
but at each level the number of elements and the nesting must match. If you are using Python 3 then there is an option to include *target
in the target_list and that will swallow a variable number of arguments.
Upvotes: 0
Reputation: 18049
This is what is called "unpacking", i believe the imap_conn.search(None, search_string
method returns 2 values (probably a tuple), this notation allows you can assign them to 2 variables in one shot.
This is equivalent to:
return_val = imap_conn.search(None, search_string)
typ = return_val[0]
dat = return_val[1]
Upvotes: 0
Reputation: 882546
In Python, you can assign and/or return more than one value, as per the following code:
def fn ():
return (7, 2)
(seven, two) = fn()
print seven
print two
print fn()
This outputs:
7
2
(7, 2)
I prefer the explicit tuple syntax (the one with the parentheses) myself since I believe it makes the intent clearer.
Upvotes: 2
Reputation: 8246
Depends what search is returning. You can unpack a result using that syntax. So for example:
>>>x, y = (1,2)
>>>x
1
>>>y
2
>>> x, y =[(1,2), [1,2,3,(1,2)]]
>>> x
(1, 2)
>>> y
[1, 2, 3, (1, 2)]
Upvotes: 0
Reputation: 21460
It is tuple unpacking, see Python documentation. If your function returns a tuple you can always unpack it using a syntax similar to a, b = func()
.
Also, you can use tuples on the fly, like a, b = b, a
can be used for swapping two values.
Upvotes: 7
Reputation: 613481
typ, dat
is a tuple. When used on the left hand side of an assignment a, b = x
it is equivalent to:
a = x[0]
b = x[1]
In your example, typ, dat = imap_conn.search(None, search_string)
is equivalent to:
search_res = imap_conn.search(None, search_string)
typ = search_res[0]
dat = search_res[1]
This technique of writing a tuple on the left hand side of an assignment is known as tuple unpacking.
Upvotes: 3