My understanding of the concept of the context in which the calculator runs is not very deep; as I understand it, the required resources, running environment, etc. will be serialized before the program is run, and then added to the CPU's task queue, waiting for the dispatch system to allocate time slice execution. Let's talk about the use of the Python context manager.
Custom Context Manager
- The most common context manager in Python is the opening and closing of files.
withopen(filename,‘r‘asfile: file.read()
Principle
- The python context uses the WITH trigger, which implements the __enter__ and __exit__ two magic methods internally.
classContextObject):def __init__( Self):Print(' AAAA ')def __enter__( Self):Print(' bbbb ')def __exit__( Self, Exc_type, Exc_val, EXC_TB):Print(' CCCC ')# Exc_type: type of exception;# Exc_val: Exception details;# EXC_TB: where the exception occurred;# If no exception occurs, the above three values are none withContext () asF:" subject Logic" Print(' xxxx ')# OutputAaaabbbbxxxxcccc
- When using the WITH Trigger Manager, first initialize execution __init__ to get an object, then execute the __enter__ method, then execute the principal program logic, and finally execute the __exit__ method.
Attention
When the program body logic executes and exits the WITH statement block or the principal logic block, the __exit__ method is automatically executed, and the exception parameters are passed in, and if there is no exception, none is passed.
If the principal logic code has an error, but the __exit__ function returns True, the With statement body Logic block exception is not thrown, terminates the program, and if none or false is returned, the exception is actively raise and the program terminates.
Summarize the full principle of the context Manager
Initialize gets a context manager object;
The exit () method of the load context manager is reserved;
Call the context Manager's enter () method, or, if there is an as F clause, assign the return value of the Enter () method to F;
Executing the body logic code block;
Call the exit () method of the context manager;
Python's context management tool Contextlib
- Python has a more elegant way of managing the context manager.
import contextlib@contextlib.contextmanagerdef test(): print(‘aaaaaa‘) try: yield1 finally: print(‘bbbbb‘)withas f: print(‘ccccc‘)# 输出aaaaaacccccbbbbb
The underlying simplified version of the principle
classContextTest (Object):def __init__( Self): Self. f= Self. Test ()def __enter__( Self):return Next( Self. f)def __exit__( Self, Exc_type, Exc_val, EXC_TB):Try:Next( Self. f)except stopiteration:return False defTest Self):Print(' aaaaaa ')Try:yield 1 finally:Print(' bbbbb ') withContextTest () asF:Print(f)Print(' KKKKKK ')
Initializes a ContextTest context Manager object object, resulting in an object's generator test ()
The exit () method of the load context manager is reserved;
Call the context Manager's enter () method, and execute the next () method to wake the test () generator and execute the code in front of the yield keyword;
Executing the principal logic code;
Call the exit () method of the context manager; The method calls the next () method to wake the generator again, executing the code after the yield keyword;
Python context Manager