Skip to content
Advertisement

Python confusion with return value in try-except-finally

Here is a piece of my code:

JavaScript

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?

Advertisement

Answer

You’re running into the difference between an identifier and a value. num += 1 is creating a new int object and assigning the num identifier to point to it. It does not change the int object the identifier is already pointing to. (For small values the int objects 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:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement