为什么 except object 不捕获 Python 中的所有内容?

Why doesn't except object catch everything in Python?

python 语言参考状态 section 7.4

For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.

那么,为什么 except object: 没有抓住一切? object 是所有异常 class 的基础 class,因此 except object: 应该能够捕获每个异常。

例如,这应该捕获 AssertionError

print isinstance(AssertionError(), object) # prints True
try:
    raise AssertionError()
except object:
    # This block should execute but it never does.
    print 'Caught exception'

我相信可以在source code for python 2.7:

中找到答案
        else if (Py_Py3kWarningFlag  &&
                 !PyTuple_Check(w) &&
                 !Py3kExceptionClass_Check(w))
        {
            int ret_val;
            ret_val = PyErr_WarnEx(
                PyExc_DeprecationWarning,
                CANNOT_CATCH_MSG, 1);
            if (ret_val < 0)
                return NULL;
        }

所以如果 w(我假设 except 语句中的表达式)不是元组或异常 class Py_Py3kWarningFlag 是set 然后尝试在 except 块中使用无效的异常类型将显示警告。

该标志是通过在执行文件时添加 -3 标志来设置的:

Tadhgs-MacBook-Pro:~ Tadhg$ python2 -3 /Users/Tadhg/Documents/codes/test.py
True
/Users/Tadhg/Documents/codes/test.py:5: DeprecationWarning: catching classes that don't inherit from BaseException is not allowed in 3.x
  except object:
Traceback (most recent call last):
  File "/Users/Tadhg/Documents/codes/test.py", line 4, in <module>
    raise AssertionError()
AssertionError