1

So let's say I have a function like this:

def dummy():
    e = 1
    try:
        return e
    finally:
        e = 2

This function returns 1, so it looks like return statement is executed before finally, so finally has no effect at all.

However, when I declare the function like this:

def dummy():
    e = {}
    e['x'] = 1
    try:
        return e
    finally:
        e['x'] = 2

The returned value is {'x': 2}, so it looks like finally is executed before return.

Could someone explain to me what happens here actually?

lipowskm
  • 31
  • 5
  • 3
    It is not that `finally` block is not executed at all. You can put a print statement in the first scenario and check that it is getting executed. In the second scenario, you are returning a dict and then finally block is executed which changes the attribute of the dict. The reference to the return dict and the dict which got changed is still same and hence you see the changed value. – AKS Jul 08 '21 at 10:43
  • You can also check [this post](https://stackoverflow.com/questions/15078519/python-dictionary-passed-as-an-input-to-a-function-acts-like-a-global-in-that-fu) for more explanation. – AKS Jul 08 '21 at 10:45
  • @AKS I figured out it is executed before return, but why `finally` block has the reference to the attribute in a variable, but doesn't have the reference to the variable itself? – lipowskm Jul 08 '21 at 10:46

0 Answers0