In Python, we’ll hear a lot about a Context Manager, so let’s explore what it is and what it does.

The use of with to open a file is the most common in Python context managers, where a cleanup is performed after leaving the statement contained in with, such as closing the file, closing the connection object, and so on.

practice

In our code practice, we ignore the fact that in the same code fragment, we open the file first and then directly do other processing to the file, because it makes no sense, the resource is occupied.

Let’s look at the following code:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
# MedusaSorcerer Script
import os


class OpenFile:
    def __init__(self) :
        self.file = None

    def open(self, path) :
        self.file = open(path, 'w')


if __name__ == '__main__':
    file_path = 'medusa.md'
    file = OpenFile()
    file.open(file_path)
    os.remove(file_path)
Copy the code

In the code, we refer to the file object as an instance property, and after that, we use the OS module to delete the file being written. After executing the modified snippet, the following should appear:

Traceback (most recent call last): File "medusa/main.py", line 19, in <module> os.remove(file_path) PermissionError: [WinError 32] Another program is using this file and the process cannot access it. : 'medusa.md' Process finished with exit code 1Copy the code

That is because deleted files are not freed. On the basis of the above, we apply the way of function:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
# MedusaSorcerer Script
import os


class OpenFile:
    def __init__(self) :
        self.file = None

    def open(self, path) :
        self.file = open(path, 'w')


def open_file(path) :
    file = OpenFile()
    file.open(path)


if __name__ == '__main__':
    file_path = 'medusa.md'
    open_file(file_path)
    os.remove(file_path)
Copy the code

This code will execute successfully because when you execute a function, temporary variables in the function will be reclaimed and freed, so the instance object of OpenFile will be freed and the instance properties will not exist and will be freed, so it will execute successfully.

Should all of our operations be wrapped in functions? With perfectly solves this problem:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
# MedusaSorcerer Script
import os

if __name__ == '__main__':
    file_path = 'medusa.md'
    with open(file_path, 'w') as f:
        print(f)
    os.remove(file_path)
Copy the code

In the with syntax, we assign the following open file object to the f variable, print the contents of the f variable in the structure, and delete the file outside the structure:

medusa\python.exe medusa/main.py
<_io.TextIOWrapper name='medusa.md' mode='w' encoding='cp936'>

Process finished with exit code 0
Copy the code

The beauty of context management is that files can still be deleted without using close().

implementation

Context management actually implements the __enter__ and __exit__ methods:

#! /usr/bin/env python
# _*_ coding: UTF-8 _*_
# MedusaSorcerer Script


class Medusa:

    def __init__(self) :
        print('__init__')

    def __enter__(self) :
        print('__enter__')

    def __exit__(self, exc_type, exc_val, exc_tb) :
        print('__exit__')


if __name__ == '__main__':
    medusa = Medusa()
    with medusa:
        print('with object')
    print('finish')
Copy the code

Here is the output:

__init__
__enter__
with object
__exit__
finish
Copy the code

We found that the magic method automatically dispatches when combined with certain syntax, so context management turns off certain objects in autodispatches.

advantages

Implementing context management simplifies our code, makes it easier to read, and does all the work with the least amount of code.








I don’t know how long it took to get sentimental. Send a lyric to oneself: yi (a) beginning baby cry cry son (two) when learn to play loose (three) is the youth story like (four) is happened to meet you lost (ten) is lonely night defeat (100) is with suspicion cut (thousand) is struggling dream wake forget (ten thousand) is iron heart leave you – ring said