【问题标题】:__exit__ swallowing TypeError__exit__ 吞下 TypeError
【发布时间】:2018-06-04 18:36:41
【问题描述】:

我在提醒自己“关键字”时无意中发现了这篇文章http://effbot.org/zone/python-with-statement.htm。我只是有一个很小的,可能很明显的问题。文章指出,这“吞下任何 TypeError”

 def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)

我不太明白这是怎么回事?快速解释将不胜感激?

【问题讨论】:

标签: python python-3.x error-handling


【解决方案1】:

如果您从 __exit__ 子句返回 True,它将阻止任何错误发生。例如:

class Foo():
    def __enter__(self):
        print("enter")
    def __exit__(self, type, value, tb):
        print("exit with", repr(value))
        return True

with Foo():
    print("inside")
    raise ValueError()

会输出

enter
inside
exit with ValueError()

但不提出任何问题,因为__exit__() 返回了True

在示例情况下,如果引发的错误是TypeError,则语句:

return isinstance(value, TypeError)

将返回True,而TypeError 将被“吞噬”。

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多