SoFunction
Updated on 2024-12-11

Python Context ManagerContent Manager

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

In Python's context manager, opening a file with is the most common use, where leaving a statement contained in with performs some cleanup-like tasks, such as closing the file, closing the connection object, and so on.

fulfill

We are in the code practice, ignored in the same code fragment, first open the file, and then directly to the file for other processing, because this does not make any sense, the resources are in the occupied situation.

First look at the code for the following test:

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


class OpenFile:
    def __init__(self):
         = None

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


if __name__ == '__main__':
    file_path = ''
    file = OpenFile()
    (file_path)
    (file_path)

In the code, we refer to the file object as an instance attribute, after which we use the os module to delete the written file. After executing the code snippet, the following will appear:

Traceback (most recent call last):
  File "medusa/", line 19, in <module>
    (file_path)
PermissionError: [WinError 32] Another program is using this file and the process cannot access it. : ''

Process finished with exit code 1

That's because the deleted file didn't get its resources released. Let's apply a function based on the above:

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


class OpenFile:
    def __init__(self):
         = None

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


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


if __name__ == '__main__':
    file_path = ''
    open_file(file_path)
    (file_path)

This code will be executed successfully because when you execute the function, the temporary variables inside the function will be recycled and released, so the instance object of OpenFile will be released, and the instance properties will not exist and will be released, so it will be executed successfully.

So should all our operations be performed using function wrappers, with the advent of with, the perfect solution to this problem:

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

if __name__ == '__main__':
    file_path = ''
    with open(file_path, 'w') as f:
        print(f)
    (file_path)

In the with syntax, the file object returned by the later open file operation is assigned to the f variable, the contents of the f variable are output in the structure, and the file is deleted outside the structure:

medusa\ medusa/
<_io.TextIOWrapper name='' mode='w' encoding='cp936'>

Process finished with exit code 0

You can still delete files without using close(), which is the beauty of context management.

realization

Context management, in fact, 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')

The following is the output:

__init__
__enter__
with object
__exit__
finish

We found that magic methods are auto-scheduled when combined with certain syntax, so the context manager shuts down certain objects during auto-scheduling.

vantage

Implementing context management can simplify our code, make it easier to read, use the least amount of code, you can do all the work.

To this article on the Python context manager Content Manager is introduced to this article, more related to the Python context manager content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!