try, except, finally, with (enter and exit) in python

The use of with in python-a very useful feature

One, try, except, finally use

def  exe_try():
    try:
        print("code started")
        raise KeyError #抛出异常
        return
    except KeyError as e:  #捕获异常
        print("key error")
        return 2
    else:
        print("other error")
        return 3
    finally: # 最后都会运行
        print("finally")
        return 4
    
if __name__ = "__main__":
    result = exe_try()
    print(result)
# code start
# key error
# finally
# 4

raiseUp key error, then enter key errorexception handling, output is supposed to be 2, why last returnit was finally4?

Because if finallythere are returnstatements in the statement, 4 will definitely be output at the end, which can be thought of as a form of stack, and it key errorwill return 2 after it is entered , but after 2 is put on the stack, the finallystatement will return 4, so the top element of the stack is output 4 first.

If you comment out the finallystatement return, the result is 2.

Two, with statement

with context management protocol: __enter__, __exit__two magic function

class Sampledef __enter__(self):
        print("enter")
        return self
    def __exit__(self,exc_type,exc_value,exc_tb):
        print("exit")
	def do_something(self):
        print("do somethong")

with Sample() as sample:
    sample.do_something()
  # enter  
  # doing something
  # exit

It can be seen from the running result that it is called first __enter__, then do_something, and finally withafter leaving the statement, it will be called by default __exit__.

With this context management protocol, we can define a class, and then use it with a withstatement, and can __enter__acquire resources in __exit__and release resources in it.

Three, subsection

For a more concise way to define a context manager, please see this blog

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106931596