Python delves into the following manager

  • 2020-04-02 14:02:31
  • OfStack

The context manager is a syntax that Python2.5 began to support to specify the scope of an object. Once in or out of the usage range, special operations are invoked (such as allocating or freeing memory for an object). Its grammatical form is with... The as...

Close the file

We do this: open the file, read and write, close the file. Programmers often forget to close files. The context manager can automatically close files when they are not needed.

Let's take a look at two programs:


# without context manager
f = open("new.txt", "w")
print(f.closed)               # whether the file is open
f.write("Hello World!")
f.close()
print(f.closed)

And:

# with context manager
with open("new.txt", "w") as f:
    print(f.closed)
    f.write("Hello World!")
print(f.closed)

Both programs actually perform the same operation. Our second program USES the context manager (with... The as...). . The context manager has blocks that belong to it. The context manager automatically closes the file when the subordinate block is finished executing (that is, without indentation) (we query whether the file is closed by f.cfsed). We are essentially using indentation to specify the scope of the file object f.

The context manager above is based on the f object's s special method with s/s (remember how we implemented various syntaxes with special methods? See special methods and multi-paradigms. When we use the context manager's syntax, we actually require Python to call the object's s/s method () before entering the block, and s/s method () when the block ends. For the file object f, it defines the __enter__ () and __exit__ () method (can see through the dir (f)). In f's s s method, there is the self.close() statement. So when using the context manager, we don't have to close the f file in plain text.

The custom

Any object that defines the methods of s () and s () can be used with the context manager. File object f is a built-in object, so f automatically comes with these two special methods and does not require customization.

Next, we define our custom object for the context manager, which is myvow:


# customized object class VOW(object):
    def __init__(self, text):
        self.text = text
    def __enter__(self):
        self.text = "I say: " + self.text    # add prefix
        return self                          # note: return an object
    def __exit__(self,exc_type,exc_value,traceback):
        self.text = self.text + "!"          # add suffix
with VOW("I'm fine") as myvow:
    print(myvow.text) print(myvow.text)

Our results are as follows:


I say: I'm fine
I say: I'm fine!

We can see that the object's text property changes as it enters and leaves context (the original text property was "I'm fine").

S/s return an object. This object is used by the context manager as a variable referred to as, i.e., myvow. With s/s (), we add the prefix ("I say: ") to myset.text. In s/s s/s, we add the suffix "! ).

Note that there are four parameters in s/s (). Exc_type, exc_value, and traceback are used to describe exceptions in the parameters of the program block (), while an exception (exception) is present. We can do corresponding processing according to these three parameters. If the normal operation ends, all three parameters are None. We did not use this feature in our program.

Conclusion:

Through the context manager, we control the properties of objects in different intervals of the program. The context manager (with EXPR as VAR) is roughly equivalent to the following flow:


# with EXPR as VAR: VAR = EXPR
VAR = VAR.__enter__()
try:
    BLOCK
finally:
    VAR.__exit__()

The context manager is a worthwhile tool because of its convenience.


Related articles: