Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try_finally question
#1
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
Reply
#2
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.
akbarza likes this post
Reply
#3
(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?
Reply
#4
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.
akbarza likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020