SoFunction
Updated on 2024-12-11

Summary of Python Context Manager Implementations

When to Consider a Context Manager

Consider using a context manager to make your code more elegant when your code logic requires the following keywords:

try:
	...
finally:
	...

The three ways to implement a context manager are described next.

Method 1 (context manager protocol)

It is always known that open() supports context managers by default. So the code to open a txt file and write to it, and then close the file can be written like this:

with open("", "w") as file:
("this is a demo")

That's the equivalent:

file = None
try:
    file = open("", "w")
    ("this is a demo")
finally:
    ()

To implement the use of with statements in Python, you need to take advantage of the context manager protocol. That is, you need to implement the __enter__ and __exit__ magic methods.

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

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

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

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


with OpenMyFile("") as file:
    ("this is a demo2")

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

At the same time, you can see that the file has been generated locally. Note that __enter__ must return the instance object, otherwise it will report an exception: AttributeError: 'NoneType' object has no attribute 'write'

This is because functions in Python return None by default.

Method 2 (@contextmanager)

Utilize the contextmanager decorator in contextlib.

from contextlib import contextmanager


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


with open_my_file("") as file:
    ("this is demo3")

# Output:
opening the txt
closing the txt

In a function decorated by @contextmanager, you need to separate two logical statements with a yield. Here the object coming out of yield will be received by the variable after as.

Method 3 (())

Utilize the closing() method in contextlib.

from contextlib import closing


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

    def write(self, string):
        (string)

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


with closing(OpenMyFile("")) as file:
    ("this is demo4")

# Output:
opening the txt
closing the txt

Unlike method 1. After wrapping the closing() method, the object's close() method is forced to be called at the end of the with statement. So when using method 3, the method to be defined is not __exit__() but close().

to this article on the Python context manager to summarize the implementation of the article is introduced to this, more related Python context manager to achieve the three methods of content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!