views:

626

answers:

3

I am new to Python, and I'm working on writing some database code using the cx_Oracle module. In the cx_Oracle documentation they have a code example like this:

import sys
import cx_Oracle

connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()

try:
    cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
    error, = exc.args
    print >> sys.stderr, "Oracle-Error-Code:", error.code
    print >> sys.stderr, "Oracle-Error-Message:", error.message

My question has to do with where the "error" object is created. What does the ", =" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)

I know that the exc.args is a singleton tuple, but I just don't understand the ", =" syntax. If I remove the comma, I get the error message, "AttributeError: 'tuple' object has no attribute 'code'".

Can someone point me to where this is documented? Thanks!

EDIT:

This works without having to unpack the tuple:

import sys
import cx_Oracle

connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()

try:
    cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
    print >> sys.stderr, "Oracle-Error-Code:", exc.args[0].code
    print >> sys.stderr, "Oracle-Error-Message:", exc.args[0].message
+5  A: 

http://www.python.org/doc/2.5.2/tut/node7.html

Look for "sequence unpacking" in section 5.3.

Matthew Christensen
Thanks! That makes sense now!
m0j0
Serves me right to post a long answer with explanations and all. By the time I finished writing mine, this one had been accepted :(
ddaa
Well, I voted yours up, ddaa, and it's now accepted, so don't feel so bad.
Matthew Christensen
I feel thoroughly gratified. Thanks.
ddaa
Yep, this answer technically answered my question first, but ddaa's answer was more detailed IMHO.
m0j0
+4  A: 

The comma serves to unpack the tuple, i.e. it extracts the single item of the tuple, and binds it to error. Without the comma, you would bind the tuple itself, rather than its content.

Andrew Beyer
+9  A: 
error, = exc.args

This is a case of sequence unpacking.

A more readable way to write the same, and the style I personally favor, is:

[error] = exc.args

There are two bits required to understand the previous example:

  1. When the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS.
  2. A one-item tuple in python is written (foo,). In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator.
ddaa