Python Forum
try_finally question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: try_finally question (/thread-40878.html)



try_finally question - akbarza - Oct-07-2023

hi
I saw the below code on the net:
def foo():
    try:
        return 1
    finally:
        return 2

    
k=foo()
print(k)
the result of running this code is 2( return result from finally). why is it? if the return in the try section does not run?
please explain.
another question that is not related to the above.
usually, when I enter this forum to see replies to my threads I go to forum>>my discussions. but there is not (I did not have seen until now) any object for creating a new thread there, so I have to go to home>>generall coding help>>post thread for creating a new thread.
is there an object or method in my discussions to create a new thread?
thanks


RE: try_finally question - deanhystad - Oct-07-2023

Finally always runs, no matter what happens in the try body. The function cannot exit after the try return because it must execute the finally body. Since the finally also returns, it replaces the return value fyom the try return.


RE: try_finally question - akbarza - Oct-08-2023

(Oct-07-2023, 11:48 AM)deanhystad Wrote: Finally always runs, no matter what happens in the try body. The function cannot exit after the try return because it must execute the finally body. Since the finally also returns, it replaces the return value fyom the try return.

thanks for reply
do you have any expression about the last question?


RE: try_finally question - snippsat - Oct-08-2023

One more,a common and advisable way to open a file.
with open("test.txt", encoding='utf-8') as fp:
    file = fp.read()
    print(file)
So this will always close the file object(fp),
The basic equivalent code(without enter, exit) for the with open() statement would look something like this:
f = open("test.txt", encoding='utf-8')
try:
    file = fp.read()
finally:
    fp.close()
print(file)
(Oct-07-2023, 11:22 AM)akbarza Wrote: usually, when I enter this forum to see replies to my threads I go to forum>>my discussions. but there is not (I did not have seen until now) any object for creating a new thread there, so I have to go to home>>generall coding help>>post thread for creating a new thread.
is there an object or method in my discussions to create a new thread?
thanks
my discussions only show your discussions,can not make new Thread from there.
Most always be forum that want to create Thread(eg General Coding Help), then Post Thread.