Python's understanding of with

Python with understanding

Tags (space separated): Python


withAs a kind 上下文管理器, Pythonthe role in can be simply understood as try...except...finallya processing flow used to replace .

with__enter__Initialize through the method, and then __exit__do the aftermath and handle exceptions in it. It withprovides a very convenient expression for some tasks that need to be set in advance and cleaned up afterwards . After the following withstatement is evaluated, the __enter__method that returns the object will be called , and __enter__the returned result will be assigned to the asfollowing variable. When the withfollowing code blocks are all executed, the __exit__()method that returns the object will be called to perform cleanup work.

Just like in file operations:

file = open("file.txt")
try:
    data = file.read()
finally:
    file.close()

After use with...as..., the code will be reduced to:

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

In the above code, the open()function will return an fileobject of type , which has an __enter__and __exit__method (you can dir(file),type(file)view it), and then call the __enter__method of the object to assign the return value to the filevariable, so there with...as...is no need to close the display when using the operation file file.

Since we know with...as...the most important thing is __enter, __exit__that we can customize a context manager.

among them:

__enter__The method will be called before entering the code block.

__exit__Will be called after leaving the code block (even if an exception is encountered in the code block).

class WithDemo:
    def __enter__(self):
        print "in __enter__"
        return "WithDemo"
        
    def __exit__(self, type, value, trace):
        print "in __exit__"
        
def get_demo_with():
    return WithDemo()
    
with get_demo_with() as demo:
    print "demo:", demo

The execution result is:

in __enter__
demo:WithDemo
in __exit__

At the beginning, it was said that the process operation that with..as..can be used instead try...except...finally..., try...finally...the situation mentioned above , what about abnormal? If you look carefully, you will find __exit__()three parameters, and these three parameters are the parameters that provide handling for exceptions.

class WithDemo:
    def __enter__(self):
        return self
        
    def __exit__(self, type, value, trace):
        print "type:", type
        print "value:", value
        print "trace:", trace
        
    def create_trace(self):
        return (1/10) + 10
        
with WithDemo() as demo:
    demo.create_trace()

Run the code and you will find that the code prints type, value, and trace.

Guess you like

Origin blog.csdn.net/weixin_42575020/article/details/107565394