Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python raise with two parameters

What does raise A, B do? And how is it different from what raise A does?

Some examples (running at the interpreter of python 2.7):

class E(Exception):
    pass
e = E()

raise Exception, e
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
__main__.E

raise Exception(e)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
Exception

raise (Exception, e)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
Exception

Thanks!

like image 988
user3033336 Avatar asked Apr 07 '14 19:04

user3033336


1 Answers

raise supports up to three arguments; the first two are the type and value, the third is a traceback object to use for the exception. The line:

raise Exception, value

is normally exactly equivalent to:

raise Exception(value)

so, creating an instance of Exception(), passing in the second value as an argument to the exception constructor.

In your example, however, the second argument is an instance of the E type, which is a subclass of Exception and thus the line:

raise Exception, e

is the equivalent of:

raise e

You could also have used an empty tuple here:

raise E, ()

or None:

raise E, None

just to increase the number of ways of raising the E exception type with no arguments; the tuple second argument specifies all arguments to be used for the E exception type; an empty tuple or None just makes that equivalent to raise E().

As for using a tuple as the first argument, that is equivalent to using raise Exception as Python will unwrap nested tuples used as the first argument.

From the raise statement documentation:

If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value.

All these rules made the statement way to complex and there were multiple ways of raising an exception that were functionally equivalent. As such the multiple-argument raise syntax has been removed from Python 3 altogether, see PEP 3109 - Raising Exceptions in Python 3000.

like image 186
Martijn Pieters Avatar answered Oct 23 '22 13:10

Martijn Pieters