Copyright: arbitrary, seeding https://blog.csdn.net/qq_32662595/article/details/85090821!
Context Manager allows you when there is a need to accurately allocate and release resources.
Demand:
There are two junction related operations need to be performed, then also place a code in the middle thereof.
with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')
Equivalent to:
file = open('some_file', 'w')
try:
file.write('Hola!')
finally:
file.close()
A common use case context manager is locking and unlocking resources, and close open files.
Based on the implementation class
Customize to open the file manager context
A context manager class, at least to define __enter__
and __exit__
methods.
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()
Using a custom manager with the:
with File(fileName ,method) as opened_file:
opened_file.write('Hola!')
Procedure :
- with the staging of the first sentence __exit__ method of the File class
- It then calls the method of the File class __enter__
- __enter__ method opens the file and return to the with statement
- Open the file handle is passed to parameters opened_file
- Use .write () to write files
- Before staging method with statement calling __exit__
- __exit__ method to close the file
Exception Handling:
- It passes unusual type, value and traceback method to __exit__
- It makes __exit__ way to handle exceptions
- If __exit__ returns True, then the exception is handled gracefully
- If __exit__ returned is anything other than True, then this exception will be thrown out with the statement.
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):
print("Exception has been handled")
self.file_obj.close()
return True
with File(fileName, 'w') as opened_file:
opened_file.undefined_function()
Based achieve generator
The decorative device (Decorators) and the generator (Generators) context manager implemented. Python has a contextlib
module dedicated to this purpose. We can use a generator function to implement a context manager.
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
yield f
f.close()
- Python interpreter encounters the yield keyword. For this reason it creates a generator instead of a normal function.
- Because this decorator, contextmanager will be called and passed into the function name (open_file) as a parameter.
- contextmanager function returns a package had to GeneratorContextManager object generator.
- GeneratorContextManager is assigned to open_file function, we are actually calling GeneratorContextManager object.