Here is a piece of my code:
def main():
num = 0
try:
raise Exception('This is the error message.')
except Exception:
num += 1
return num
finally:
num += 1
a = main()
print(a)
The returning value is 1 instead of 2, this does not make a lot of sense for me.
I thought it would return 2 since finally should execute before returning the value.
Can someone help me to understand this?
You're running into the difference between an identifier and a value.
num += 1is creating a newintobject and assigning thenumidentifier to point to it. It does not change theintobject the identifier is already pointing to. (For small values theintobjects are cached but that's an implementation detail)You can see the difference with an operation that does mutate the object in the below code: