Explanation of python Context Management Using Scenario Example

  • 2021-09-12 01:37:43
  • OfStack

1. Context management usage scenarios

In any scenario where code is inserted before and after a code block, this is similar to a decorator.

Resource management class: application and recovery, including opening files, network connection, database connection, etc.;

Permission verification.

2. Examples


>>> with Context():
...   raise Exception #  Throw an exception directly 
...
enter context
exit context
Traceback (most recent call last):
 File "/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
  exec(code_obj, self.user_global_ns, self.user_ns)
 File "<ipython-input-4-63ba5aff5acc>", line 2, in <module>
  raise Exception
Exception

Extension of knowledge points:

Solution to python Context Manager Exception Problem

Exception instance

If we need special handling of exceptions, we can implement custom logic in this method.

The reason why with can automatically close file resources is that the built-in file object implements the context manager protocol. The __enter__ method of this file object returns the file handle, and the file resource is closed in __exit__. In addition, when an exception occurs in the with syntax block, it will throw an exception to the caller.


class File:
 def __enter__(self):
 return file_obj
 def __exit__(self, exc_type, exc_value, exc_tb):
 # with  Release file resources on exit 
 file_obj.close()
 #  If  with  There is an abnormality in it   Throw an exception 
 if exc_type is not None:
  raise exception

Handling exception instance extensions in the __exit__ method:


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('demo.txt', 'w') as opened_file:
 opened_file.undefined_function()
 
# Output: Exception has been handled

Related articles: