【问题标题】:Python "with" statement is throwing error [duplicate]Python“with”语句抛出错误[重复]
【发布时间】:2021-04-16 10:57:55
【问题描述】:

这是一个示例代码:

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

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

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

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

感谢您的帮助

【问题讨论】:

  • __exit__ 甚至没有到达,因为__enter__ 没有成功完成。

标签: python with-statement


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 2021-10-18
    • 1970-01-01
    • 2015-05-29
    • 2022-08-16
    • 2015-01-05
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多