Python“with”语句抛出错误

问题描述

这是一个示例代码

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__ 函数中使用字符串连接,这样如果 text 参数是一个 int,就会出现一个 TypeError(但不应该因为 with 语句而被抛出)

来自python docs

如果在分配给目标列表的过程中发生错误,它将被视为套件中发生的错误

如果套件因异常退出,并且 exit() 方法的返回值为 false,则重新引发异常。如果返回值为真,则异常被抑制,并继续执行 with 语句之后的语句。

所以这里 __exit__ 返回 True 那么为什么当我运行这个示例代码时,会抛出一个错误

感谢您的帮助

解决方法

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