Python Programming ContextManager Context Manager Explanation

  • 2021-12-04 19:13:02
  • OfStack

Directory What is a Context Manager Official Explanation A simple sentence __enter__ (self) __exit__ (self, exc_type, exc_value, exc_traceback) What are the common context managers? Open File Split Understanding Execution Order Custom Context Manager Class-based Context Manager Summary Generator-based Context Manager Summary Tutorial for with Statements

What is a context manager

Official explanation

The context manager is an object that defines the runtime context to be established when the with statement is executed. The context manager handles the runtime context required for entry and exit to execute the code block. The context manager is usually called using the with statement, but can also be used by calling their instance methods directly

1 meal is as fancy as a tiger, and I don't quite understand the result

A simple sentence

The object that contains both __enter__ () and __exit__ () methods is the context manager

__enter__(self)

Enter the method automatically called by the context manager

This method is executed before the with... as... code block executes

If the with statement has an as clause and the method has a return value, the return value of the method is assigned to the variable following the as clause, most commonly with open ('file_path', 'w') as file:

This method can return multiple values, so you can also specify multiple variables after the as clause. (Multiple variables must be enclosed by "()" to form tuples.)

__exit__(self, exc_type, exc_value, exc_traceback)

Exiting the method automatically called by the context manager will return a value of Boolean type

This method is executed after the with... as... code block is executed

If the with... as... code block ends successfully, the program automatically calls the method, and all three parameters are None

If an exception occurs during the execution of the with... as... code block, the exception information is obtained through sys.exc_info (), and the three parameter values are: exception type, exception information and exception backtracking information type

What are the common context managers?

Open a file


with open('file_path', 'w') as file:
    file.write('hello world !')

Split understanding

Context expression: with open ('file_path', 'w') as file:

Context Manager: open ('file_path', 'w')

file: It can be understood as a resource object

Execution sequence

First execute the __enter__ () method of open () and assign the return value to file

Execute file. write ('hello world! ')

Finally, the __exit__ () method of open () is executed

Custom Context Manager

There are actually two ways

Implementation of Context Manager Based on Class

You only need to add 1 __enter__ and 1 __exit__ method to the object


import sys
class Resource:
    def __init__(self, name):
        self.name = name
        print("==  Initialization method  ==")
 
    def __enter__(self):
        print(f"**  Enter the context manager to automatically call: name is {self.name}")
        #  You can return any type of value 
        return {"name": self.name}
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"##  Exit context manager automatic call: ", sys.exc_info(), exc_type, exc_val, exc_tb)
        if exc_tb is None:
            print(" Close resources when there are no exceptions ")
        else:
            print(" Close resources when an exception is encountered ")

The context manager is invoked through with

Also known as: Managing resources with with... as...


with Resource(" Small pineapple ") as r:
    print(r)

console Output Result

= = initialization method = =
** Enter the context manager and automatically call: name is Pineapple
{'name': 'Little Pineapple'}
# # Exit context manager automatic call: (None, None, None) None None None
Close resources when there are no exceptions

The three parameter values of the __exit__ () method are all None

with code block throws exception


with Resource(" Abnormal small pineapple ") as r:
    print('[with Code block ]  Code before exception ')
    raise Exception(" Throw out  Exception")
    print('[with Code block ] ~~~~~~~~ Code after exception ')

console Output

= = initialization method = =
** Enter the context manager and automatically call: name is abnormal pineapple
[with Code Block] Code before exception
# # Exit context manager automatically calls: ( < class 'Exception' > , Exception ('Exception thrown'), < traceback object at 0x10e203200 > ) < class 'Exception' > Exception thrown < traceback object at 0x10e203200 >
Close resources when an exception is encountered
Traceback (most recent call last):
File "/Users/polo/Documents/pylearn/Chapter 7: File Correlation/1_ Context Manager.py", line 36, in < module >
raise Exception ("Exception thrown")
Exception: Exception thrown

When the code block throws an exception, you can see that the three parameter values of the __exit__ () method are indeed derived from sys.exc_info ()

Summarize The __exit__ () method is eventually automatically called regardless of whether the with code block has an exception or not When an exception is thrown, __exit__ () returns None by default and throws the exception to the outside again, allowing code other than with... as... to handle the exception Conversely, if True is returned, the exception is ignored and no longer handled

__exit__ () returns True


    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"##  Exit context manager automatic call: ", sys.exc_info(), exc_type, exc_val, exc_tb)
        if exc_tb is None:
            print(" Close resources when there are no exceptions ")
        else:
            print(" Close resources when an exception is encountered ")
            return True
 
 
#  Run again 
with Resource(" Abnormal small pineapple ") as r:
    print('[with Code block ]  Code before throwing exception ')
    raise Exception
    print('[with Code block ]  Code after throwing an exception ')

console Output

= = initialization method = =
** Enter the context manager and automatically call: name is abnormal pineapple
[with Code Block] Code before exception
# # Exit context manager automatically calls: ( < class 'Exception' > , Exception ('Exception thrown'), < traceback object at 0x100e29200 > ) < class 'Exception' > Exception thrown < traceback object at 0x100e29200 >
Close resources when an exception is encountered

No More Throwing Exceptions

Context Manager Based on Generator

Define the generator-based context manager you need through the decorator contextlib. contextmanager


from contextlib import contextmanager 
@contextmanager
def file_manager(name, mode):
    try:
        # 1 , open the file 
        file = open(name, mode)
        # 2 Returns the file resource object 
        yield file
    finally:
        # 3 , close the file 
        file.close() 
with file_manager('a.txt', 'w') as file:
    print(file)
    file.write('hello world')

The function file_manager () is a generator

When the with as statement is executed, the file resource object is obtained, the generator pauses the execution, returns the file resource object and assigns the value to file

After the with statement is executed, the generator continues to execute the remaining code, closes the file, and releases the resource

Summarize The __enter__ () and __exit__ () methods are no longer used when defining a generator-based context manager But you need to add decorator @ contextmanager

Tutorial for with Statements

https://www.ofstack.com/article/172132.htm

The above is the Python programming ContextManager context manager explains the details, more about Python programming Context Manager information please pay attention to other related articles on this site!


Related articles: