Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie Python Question about tuples

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
like image 804
m0j0 Avatar asked Nov 19 '08 22:11

m0j0


1 Answers

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.
like image 166
ddaa Avatar answered Sep 29 '22 07:09

ddaa