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
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:
(foo,)
. In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator.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