理解在上下文管理器类中返回self的目的

时间:2015-12-18 22:24:57

标签: python python-2.7 class with-statement contextmanager

尝试理解上下文管理器如何捕获错误,但更具体地说,__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__()只是回归自我?

0 个答案:

没有答案