If I try the following code (in Python 3.2.2),
def f():
raise Exception
x = f()
then it appears that x
is untouched - it either remains undefined or keeps whatever value it had previously. Is this behaviour guaranteed whenever the right hand side of an assignment throws an exception? I realise this is a very basic question, but I can't find much information about how exactly assignment works. More generally, is the entire right hand side always evaluated before anything relating to the assignment happens? Is this even true when using setattr
, assigning to an element of a list, or using tuple unpacking (i.e. something like x, y = y, f()
)?
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
The Python language reference specifies this:
http://docs.python.org/reference/expressions.html#evaluation-order
Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
The right side is evaluated, then the left side, then the assignment itself happens. Thus,
def x():
print "x"
fail()
def y():
print "y"
fail()
x().a = y()
is guaranteed to print "y" and fail with NameError; it will never raise "x", or attempt any assignment.
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