尝试理解上下文管理器如何捕获错误,但更具体地说,__enter__()
方法在创建用作上下文管理器的类中的作用,它在“错误捕获”过程中如何工作,以及为什么self
是__enter__()
方法中返回的全部内容。
鉴于以下使用上下文管理器来捕获错误:
import unittest
class InvoiceCalculatorTests(unittest.TestCase):
def test_no_pay(self):
with self.assertRaises(ValueError):
pay = divide_pay(0, {"Alice": 3.0, "Bob": 3.0, "Carol": 6.0})
以下是我认为assertRaises
的{{3}}:
class _AssertRaisesContext(_AssertRaisesBaseContext):
"""A context manager used to implement TestCase.assertRaises* methods."""
_base_type = BaseException
_base_type_str = 'an exception type or tuple of exception types'
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
if self.obj_name:
self._raiseFailure("{} not raised by {}".format(exc_name,
self.obj_name))
else:
self._raiseFailure("{} not raised".format(exc_name))
else:
traceback.clear_frames(tb)
if not issubclass(exc_type, self.expected):
# let unexpected exceptions pass through
return False
# store exception, without traceback, for later retrieval
self.exception = exc_value.with_traceback(None)
if self.expected_regex is None:
return True
expected_regex = self.expected_regex
if not expected_regex.search(str(exc_value)):
self._raiseFailure('"{}" does not match "{}"'.format(
expected_regex.pattern, str(exc_value)))
return True
我已经尝试通过source code获得一些见解,但是要了解其中包含的内容,这有点超出了我目前的知识/理解。有人可以用相对门外汉的术语解释__enter__()
和__exit__()
在这里“捕捉”ValueError的过程中的作用,以及为什么__enter__()
只是回归自我?