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?
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.
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.
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.
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]
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.