Summary of Python context manager implementation methods

Time:2021-11-22
catalogue
  • When can I consider a context manager
  • Method 1 (context manager protocol)
  • Method 2 (@ contextmanager)
  • Method 3 (contextlib. Closing())

When can I consider a context manager

When your code logic needs the following keywords, you can consider using context manager to make your code more elegant:


try:
	...
finally:
	...

Next, we introduce three methods to implement the context manager.

Method 1 (context manager protocol)

As we all know, open () supports the context manager by default. Therefore, the code to open a TXT file, write content to it, and then close the file can be written as follows:


with open("1.txt", "w") as file:
file.write("this is a demo")

This is equivalent to:


file = None
try:
    file = open("1.txt", "w")
    file.write("this is a demo")
finally:
    file.close()

To implement the use of the with statement in Python, you need to use the context manager protocol. That is, it needs to be realized__ enter__ And__ exit__ Two magic methods.

class OpenMyFile(object):
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        print("opening the txt")
        self.f = open(self.path, "w")
        return self

    def __exit__(self, *args, **kwargs):
        print("closing the txt")
        self.f.close()

    def write(self, string):
        print("writing...")
        self.f.write(string)


with OpenMyFile("2.txt") as file:
    file.write("this is a demo2")

#Output:
opening the txt
writing...
closing the txt

At the same time, you can see that the 2.txt file is generated locally. It should be noted that__ enter__ Return the instance object, otherwise an exception will be reported: attributeerror: ‘nonetype’ object has no attribute ‘write’

This is because functions in Python return none by default.

Method 2 (@ contextmanager)

Use the contextmanager decorator in contextlib.

from contextlib import contextmanager


@contextmanager
def open_my_file(path):
    print("opening the txt")
    f = open("3.txt", "w")
    yield f
    print("closing the txt")
    f.close()


with open_my_file("3.txt") as file:
    file.write("this is demo3")

#Output:
opening the txt
closing the txt

In the function decorated with @ contextmanager, two logical statements need to be separated by yield. Here, the object produced by yield will be received by the variable after as.

Method 3 (contextlib. Closing())

Use the closing () method in contextlib.

from contextlib import closing


class OpenMyFile(object):
    def __init__(self, path):
        print("opening the txt")
        self.f = open(path, "w")

    def write(self, string):
        self.f.write(string)

    def close(self):
        print("closing the txt")
        self.f.close()


with closing(OpenMyFile("4.txt")) as file:
    file.write("this is demo4")

#Output:
opening the txt
closing the txt

Different from method 1. After being wrapped by the closing () method, the close () method of the object will be forcibly called at the end of the with statement. Therefore, when using method 3, the method to be defined is not__ exit__ () but close ().

This is the end of this article on the summary of the implementation methods of Python context manager. For more information about the three methods of Python context manager implementation, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Issue 8: front end nine inspiration sharing

Issue 8: front end nine inspiration sharing 1、 Set the verification of GIT commit(husky:^5Configuration before version is different from here) In general, every time we executeGit commit – M ‘submit information’The verification of commit information and code style will be triggered. If the verification fails, the commit will fail. How are these verifications added to […]