[Python] with context manager principle and application

This blog mainly summarizes usage, custom context manager, and __exit__ parameter related content. The

with statement is a simplified syntax provided by Pyhton. It is suitable for accessing resources. It ensures that the necessary "cleanup" operations are performed regardless of whether an exception occurs during use, and the resources are released. The with statement is mainly for simplification. Code operation.

with: Automatically close

# after the file is used to create a file test.txt, open if it exists, write Hello Python
#Create/Open File
f = open('test.txt', 'w')
F.write("Hello Python")
# Close this file
F.close()


#用with
With open('test.txt', 'w') as f:
    F.write('Python')

can be found: when writing code with the with statement, the code will be more concise, no need to close the file.

with the execution process:

When executing the with statement, first execute the open code with the

after executing the code, the result of the code will be saved to f in

Then implement the actual operation to be executed below

, after the operation, do not need to write the file to close the operation, the file will automatically close

with the execution principle after use

actually, in When the file is manipulated, it is not necessary to close the file, but the file close operation is already written in the protocol method in the context manager of with. When the file operation is completed, the with statement automatically calls the close statement in the context manager to close the file resource.

Context Manager

ContextManager , context is the literal literal translation, used in the program to indicate the context before and after the code execution. There are two methods __enter__ and __exit__ in the context manager. With the example of with, the __enter__ method will be executed when the statement following with is executed, which is generally used to process the content before the operation. For example, some create objects, initialize, etc.; __exit__ method will be executed after the execution of the code in with, generally used to deal with some after-sales work, such as file closure, database shutdown.

Customize a context manager, simulate with file operations
Class MyOpen(object):
    Def __init__(self,path,mode):
        # Record the file path and mode to be operated
        Self.__path = path
        Self.__mode = mode

    Def __enter__(self):
        Print('code execution to __enter__...')
        # open a file
        Self.__handle = open(self.__path,self.__mode)
        # Returns an open file object reference, which is used to assign a value to the variable f after as
        Return self.__handle

    # Exit method, used to achieve after-treatment work
    Def __exit__(self, exc_type, exc_val, exc_tb):
        Print('code execution to __exit__...')
        Self.__handle.close()

# a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Append mode will be used when the file is opened. If the file does not exist, create a new file for reading and writing.
With MyOpen('test.txt','a+') as f:
    #Create a write file
    F.write("Hello Python!!!")
    Print ("file write success") 

Execution result:

By executing the order, you can see that the file write operation is executed, the __exit__ method is automatically called, and the post-processing work is done. The

__exit__ method parameter has three parameters in the

__exit__ method to receive the processing exception. If the code is abnormal at runtime, the exception will be saved here.

exc_type : Exception type

exc_val : Outlier

exc_tb : Exception backtracking

# Write a program that divides two numbers and then puts the divisor into 0
Class MyCount(object):
    # Receive two parameters
    Def __init__(self,x, y):
        Self.__x = x
        Self.__y = y
    # Return an address (substantially received by the variable after as), the instance object will execute the method in MyCount: div()
    Def __enter__(self):
        Print('code execution to __enter__...')
        Return self
    Def __exit__(self, exc_type, exc_val, exc_tb):
        Print("code execution to __exit__...")
        If exc_type == None:
            Print('Program is no problem')
        Else:
            Print('The program has a problem, if you can understand it, the problem is as follows:')
            Print('Type: ', exc_type)
            Print('Value:', exc_val)
            Print('TreacBack:', exc_tb)

        # Return value determines whether the captured exception continues to be thrown out
        # If it is False then it will continue to be thrown out, the program will see the system prompts the exception information
        # 如果 True will not be thrown out, the program can not see the system prompt information, can only see the output in the else
        Return True

    Def div(self):
        Print("code execution to division div")
        Return self.__x / self.__y


With MyCount(1, 0) as mc:
    Mc.div()

Execution result:

can see that the system did not throw an exception, but __exit__ caught the exception and threw it in our way.