Understanding some Python code
I'm working my way through Gmail access using imaplib and came across:
# Count the unread emails
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount
I just wish to know what:
status,
does in front of the "response =". I would google it, but I have no idea what I开发者_如何学运维'd even ask to find an answer for that :(.
Thanks.
When a function returns a tuple, it can be read by more than one variable.
def ret_tup():
return 1,2 # can also be written with parens
a,b = ret_tup()
a and b are now 1 and 2 respectively
See this page: http://docs.python.org/tutorial/datastructures.html
Section 5.3 mentions 'multiple assignment' aka 'sequence unpacking'
Basically, the function imap_server returns a tuple, and python allows a shortcut that allows you to initialize variables for each member of the tuple. You could have just as easily done
tuple = imap_server.status('INBOX', "(UNSEEN)")
status = tuple[0]
response = tuple[1]
So in the end, just a syntactic shortcut. You can do this with any sequence-like object on the right side of an assignment.
Though the answers given are certainly sufficient, an quick application of this python feature is the ease of swapping values.
In a normal language, to exchange the values of variables x
and y
, you would need a temporary variable
z = x
x = y
y = z
but in python, we can instead shorten this to
x, y = y, x
精彩评论