with usage in python

Preface

The with statement is suitable for accessing resources, ensuring that necessary "cleanup" operations are performed regardless of whether an exception occurs during use, and resources are released.

For example, the file is automatically closed after use/the lock is automatically acquired and released in the thread.

Question leads

The following code:

file = open("1.txt")
data = file.read()
file.close()

There are two problems with the above code:
(1) File reading is abnormal, but no processing is done;
(2) You may forget to close the file handle;

Improve

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
try:
    f = open('xxx')
except:
    print('fail to open')
    exit(-1)
try:
    do something
except:
    do something
finally:
    f.close()

Although this code works well, it is verbose.
Using with can reduce verbosity and automatically handle exceptions generated by the context. Such as the following code:

with open("1.txt") as file:
    data = file.read()

with works principle

(1) After the statement following with is evaluated, the "–enter–()" method of the returned object is called, and the return value of this method will be assigned to the variable following as;
(2) When the code behind with After all the blocks are executed, the "–exit–()" method of the previously returned object will be called.
Code example of with working principle:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Sample:
    def __enter__(self):
        print "in __enter__"
        return "Foo"
    def __exit__(self, exc_type, exc_val, exc_tb):
        print "in __exit__"
def get_sample():
    return Sample()
with get_sample() as sample:
    print "Sample: ", sample

The running results of the code are as follows:

in __enter__
Sample:  Foo
in __exit__

As you can see, the entire running process is as follows:
(1) The enter() method is executed;
(2) The return value of the enter() method, in this example, is "Foo", which is assigned to the variable sample;
(3) The code block is executed , Print the value of the sample variable as "Foo";
(4) The exit() method is called;

[Note:] There are 3 parameters in the exit() method, exc_type, exc_val, and exc_tb. These parameters are quite useful in exception handling.

  • exc_type: wrong type
  • exc_val: the value corresponding to the error type
  • exc_tb: where the error occurred in the code

Sample code:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Sample():
    def __enter__(self):
        print('in enter')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print "type: ", exc_type
        print "val: ", exc_val
        print "tb: ", exc_tb
    def do_something(self):
        bar = 1 / 0
        return bar + 10
with Sample() as sample:
    sample.do_something()

Program output:

in enter
Traceback (most recent call last):
type:  <type 'exceptions.ZeroDivisionError'>
val:  integer division or modulo by zero
  File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 36, in <module>
tb:  <traceback object at 0x7f9e13fc6050>
    sample.do_something()
  File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 32, in do_something
    bar = 1 / 0
ZeroDivisionError: integer division or modulo by zero

Process finished with exit code 1

to sum up

In fact, when an exception is thrown in the code block following with, the exit() method is executed. When developing the library, operations such as cleaning up resources and closing files can all be placed in the exit() method.
In short, the with-as expression greatly simplifies the work of writing finally each time, which is of great help to the elegance of the code.
If there are multiple items, you can write:

With open('1.txt') as f1, open('2.txt') as  f2:
    do something

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108489882