Python: exceptions in assignments
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Question
01:00 Accepted answer (Score 14)
01:44 Answer 2 (Score 0)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/8493...
Accepted answer links:
http://docs.python.org/reference/express...
Answer 2 links:
[assignment statement]: http://docs.python.org/py3k/reference/si...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #exception #exceptionhandling
#avk47
ACCEPTED ANSWER
Score 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.
ANSWER 2
Score 0
The Python documentation concerning the assignment statement does not explicitly say that the left hand side of an assignment is never touched when the right hand side raises an exception, but after reading this article, it seems to turn out that the only way to avoid the assignment is to raise an Exception.
Conclusion: the left hand side of an assignment is never touched if an exception is raised