Exceptions, assigning a tuple

Erik Max Francis max at alcyone.com
Fri Nov 21 02:09:50 EST 2003


Derek Fountain wrote:

> What I don't understand is the assignment of a tuple in the except
> clause.
> The O'Reilly Nutshell book says "The optional target is an identifier
> that
> names a variable that Python binds to the exception object just before
> the
> exception handler executes". This doesn't make sense in this case:
> 
> except IOError, (errno, strerror):
> 
> The target is a tuple of 2 variable names so how can it bind "the
> exception
> object" to them? The documentation for try/except says that "the
> exception's parameter is assigned to the target". So what, exactly, is
> an
> "exception's parameter"?

This is just using tuple unpacking in assignment:

>>> tup = 1, 2, 3
>>> x, y, z = tup
>>> x
1
>>> y
2
>>> z
3

This syntax can be used anywhere an lvalue is allowed, which might
include the "variable" of a for statement:

>>> for x, y in [(1, 2), (3, 4), (5, 6)]:
...  print x, y
... 
1 2
3 4
5 6

and the "variable" in a try/except clause is just another example of
this.  The "exception's parameter" is a 2-tuple, consisting of the errno
and the strerror.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ 
\__/ Yes I'm / Learning from falling down / Heavily
    -- Lamya




More information about the Python-list mailing list