5

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.

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.