with Statement (Context Management Protocol) in Python

There are always such tasks in normal work. They need to prepare before starting, then do the task, and then finish cleaning up.... For example, to read a file, it needs to be opened, read, and closed first.

At this time, you can use with to simplify the code, which is very convenient

1. No with statement

f = open ('./test.txt')
f.read()
f.close()

2. Use the with statement

with open('./test.txt') as f:
    f.read()

 

How does with work?

with contains __enter__ and __exit__ methods, the execution order is, before the statement below with is not executed, execute the __enter__ method first, after the execution of the statement below with ends, execute __exit__ last.

Customize a context management protocol and see how it works

class Context():
    def __enter__(self):
        print('start')
        return self
    def __exit__(self,*unused):
        print('over')
    def dosomething(self):
        print('dosomething')


with Context() as ctx:
    ctx.dosomething()

 print result

start 
dosomething
over


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325343543&siteId=291194637