Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: exceptions in assignments

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

like image 893
James Avatar asked Dec 13 '11 16:12

James


People also ask

What are the exceptions in Python?

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.

How do you use exceptions in Python?

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.


1 Answers

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.

like image 167
Glenn Maynard Avatar answered Nov 12 '22 23:11

Glenn Maynard