The context manager allows you to , Allocate and release resources precisely .
The most extensive case of using context manager is with Statement .
Imagine that you have two related operations that need to be performed in pairs , Then put a piece of code between them .
Context manager is designed to let you do this . for instance :
with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')
The above code opens a file , Wrote some data into it , Then close the file . If an exception occurs when writing data to a file , It will also try to close the file . The above code is equivalent to this one :
file = open('some_file', 'w')
try:
file.write('Hola!')
finally:
file.close()
When compared with the first example , We can see , By using with, A lot of boilerplate code (boilerplate code) Has been eliminated . This is it. with The main advantages of statements , It ensures that our files will be closed , Instead of focusing on how nested code exits .
A common use case for context manager , It is the locking and unlocking of resources , And close open files ( As I've shown you ).
Let's see how to implement our own context manager . This will give us a more complete understanding of what is happening behind these scenes .
A class of context manager , At least define __enter__ and __exit__ Method .
Let's construct our own context manager for opening files , And learn the basics .
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
By defining __enter__ and __exit__ Method , We can do it in with Use it in statements . Let's try :
with File('demo.txt', 'w') as opened_file:
opened_file.write('Hola!')
our __exit__ The function takes three arguments . These parameters are for each context manager class __exit__ Methods are necessary . Let's talk about what happened at the bottom .
1. with The statement is temporarily stored File Class __exit__ Method
2. And then it calls File Class __enter__ Method
3. __enter__ Method to open the file and return to with sentence
4. The open file handle is passed to opened_file Parameters
5. We use .write() To write a file
6. with Statement before calling __exit__ Method
7. __exit__ Method closes the file