Python "with" 语句抛出错误

Python "with" statement is throwing error

这是一个示例代码:

class test :
    def __init__(self, text) :
        self.text = text
    def __enter__(self) :
        print("some text" + self.text)
    def __exit__(self, *args) :
        self.text = None
        print(args)
        return True

with test("hello world") :
    pass
with test(12) :
    pass

我在 __enter__ 函数中使用字符串连接,这样如果文本参数是一个 int,就会出现 TypeError(但由于 with 语句不应抛出)

来自python docs

If an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be.

If the suite was exited due to an exception, and the return value from the exit() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

所以这里 __exit__ return 是的,为什么当我 运行 这个示例代码时,会抛出错误?

感谢您的帮助

代码中的第二个示例从不调用 __exit__ 方法,因为 __enter__ 方法会引发错误。传递给 __exit__ 的所有错误处理都发生在 __enter__ 完成 .

之后的代码块中