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.
Here are some good resources to help you learn the Python basics: Learn Python the Hard Way — a book that teaches Python concepts from the basics to more in-depth programs. Dataquest – Python for Data Science Fundamentals Course — I started Dataquest to make learning Python and data science easier.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With