In Python, we often hear about the context manager. Let’s discuss what it is and what its function is.
In the context manager in Python, using with to open a file is the most used. After leaving the statements contained in with, some cleanup like operations will be performed, such as closing the file, closing the connection object and so on.
When we practice the code, we ignore that in the same code fragment, we first open the file and then directly process the file, because it makes no sense and the resources are occupied.
First look at the following detection code:
#!/usr/bin/env python # _*_ coding: UTF-8 _*_ # MedusaSorcerer Script import os class OpenFile: def __init__(self): self.file = None def open(self, path): self.file = open(path, 'w') if __name__ == '__main__': file_path = 'medusa.md' file = OpenFile() file.open(file_path) os.remove(file_path)
In the code, we reference the file object in the way of instance attribute. After that, we use the OS module to delete the written file. After executing the modified code fragment, the following contents will appear:
Traceback (most recent call last):
File “medusa/main.py”, line 19, in <module>
Permissionerror: [winerror 32] this file is in use by another program and cannot be accessed by the process.: ‘ medusa. md’
Process finished with exit code 1
That’s because the deleted file has not been released. Based on the above, we apply functions:
#!/usr/bin/env python # _*_ coding: UTF-8 _*_ # MedusaSorcerer Script import os class OpenFile: def __init__(self): self.file = None def open(self, path): self.file = open(path, 'w') def open_file(path): file = OpenFile() file.open(path) if __name__ == '__main__': file_path = 'medusa.md' open_file(file_path) os.remove(file_path)
This code will be executed successfully. The reason is that when you execute the function, the temporary variables in the function will be recycled and released. Therefore, the instance object of openFile will be released, and the instance attribute will not exist, so it will be executed successfully.
Should our operations be performed in the way of function wrapping? The emergence of with has perfectly solved this problem:
#!/usr/bin/env python # _*_ coding: UTF-8 _*_ # MedusaSorcerer Script import os if __name__ == '__main__': file_path = 'medusa.md' with open(file_path, 'w') as f: print(f) os.remove(file_path)
In the with syntax, assign the following operation of opening a file and the returned file object to the f variable, output the content of the f variable in the structure, and delete the file outside the structure:
<_io.TextIOWrapper name=’medusa.md’ mode=’w’ encoding=’cp936′>
Process finished with exit code 0
Without using close (), files can still be deleted, which is the beauty of context management.
Context management is actually implemented__ enter__ And__ exit__ method:
#!/usr/bin/env python # _*_ coding: UTF-8 _*_ # MedusaSorcerer Script class Medusa: def __init__(self): print('__init__') def __enter__(self): print('__enter__') def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__') if __name__ == '__main__': medusa = Medusa() with medusa: print('with object') print('finish')
The following are the output results:
We found that the magic method will automatically schedule after combining some syntax. Therefore, in the context management, some objects are closed in the automatic scheduling.
Implementing context management can simplify our code, make the code easier to read, and use the least amount of code to complete all the work.
This is the end of this article about Python context manager content manager. For more information about Python context manager, please search previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!