Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding some Python code

Tags:

python

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.

like image 871
Markus Avatar asked Jul 12 '11 03:07

Markus


People also ask

How do I read a Python program?

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.


3 Answers

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

like image 123
cwallenpoole Avatar answered Oct 18 '22 16:10

cwallenpoole


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.

like image 41
cemulate Avatar answered Oct 18 '22 17:10

cemulate


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
like image 22
Whoopska Avatar answered Oct 18 '22 16:10

Whoopska