with context management protocol

Posted by talor123 on Fri, 05 Jun 2020 10:40:52 +0200

Recently, I want to simulate the implementation of a framework involving with. Let's study it!

Here is a common way to write Automatically release file handle after running

with open("./abc.txt","r") as f: 
    data = f.read()

#Automatically release resources after running
with tf.Session() as sess:  
    result = sess.run([product])
    print(result)

with is a context management protocol to simplify try...except...finally When defining the syntax object, you need two methods: enter and exit enter() runs before the code block wrapped with the with statement is executed, initializes, and assigns the return value to the variable after as The code block after with is executed after exit(). with is often used to access resources to ensure the final release of resources, such as "clean up" operations, such as file close, thread release, etc.

Let's demonstrate this syntax by simulating with open() as f

class OPEN:
    def __init__(self,path,ty):
	self.path = path  	#route
	self.opentype = ty	#Operation type, read-only or write
	self.file = None  	#File handle
    #Open file, return handle, feel effect and__ init__ () similar
    def __enter__(self):
	print("implement__enter__()")
	self.file = open(self.path,self.opentype) 
	print("file already open")
	return self.file 
    #When the with code block is completed, it will execute automatically
    def __exit__(self, exc_type, exc_val, exc_tb):
	print("implement__exit__()")
	self.file.close()	
	print("File close")

path = "./abc.txt"
with OPEN(path,"r") as f:
    print("read file")
    data = f.read()
    print(data)
//The output is as follows:
"""
//Execution__ enter__ ()
//file already open
//read file
//This is a test txt

//Execution__ exit__ ()
//File close
"""

#About exceptions #If there is no exception, the following three values are None #exc_type if an exception is thrown, the type of the exception is obtained here #exc_ If Val throws an exception, the exception content will be displayed here #exc_tb if an exception is thrown, the location is shown here

class OPEN:
    def __init__(self,path,ty):
	self.path = path
	self.opentype = ty
	self.file = None

    def __enter__(self):
	print("implement__enter__()")
	self.file = open(self.path,self.opentype)
	print("file already open")
	return self.file 

    def __exit__(self, exc_type, exc_val, exc_tb):
	print("implement__exit__()")
	self.file.close()
	print("File close")
	print(exc_type) #If there is no exception, it is None. If there is an exception, it will display the exception information, but it will not affect the system error reporting
	print(exc_val)
	print(exc_tb)
	#If the return value is True, the exception will continue to run the code outside the code block (the run will not end)
	#If there is no return value or other value, the code will be terminated if an exception occurs
	return False

path = "./abc.txt"
with OPEN(path,"r") as f:
    print("read file")
    data = f.read()
    print(xyz) #Undefined variables on purpose
    print(data)
print("Run here")
//The output is as follows:
"""
//Execution__ enter__ ()
//file already open
//read file
//Execution__ exit__ ()
//File close
<class 'NameError'>
name 'xyz' is not defined
<traceback object at 0x7f70075c68c8>
Traceback (most recent call last):
  File "test.py", line 572, in <module>
	print(xyz)
NameError: name 'xyz' is not defined
"""

If set__ exit__ () returns True The output is as follows

(it can be seen that the code following the exception in the with code block is not executed, but the code outside the code block is executed):

"""
Execution__ enter__ ()
file already open
 read file
 Execution__ exit__ ()
File close
<class 'NameError'>
name 'xyz' is not defined
<traceback object at 0x7f468b9bf908>
Run here

"""

Topics: Programming Session