Alex Rivera | Logout

Python: exceptions in assignments

Asked 2011-12-13T16:59:23.277
12

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())?

Edit
Report

1 Answer

14

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.

answered 2011-12-13T17:59:29.820

Your Answer