如何查找Python内置标准Exception类的原始实现源代码
Python内置Exception类源码获取与定义说明
源码查找路径
Python内置的Exception类属于C实现的内置类型,因此inspect.getsource()无法读取其源码,该类的实现位于CPython源码的Objects/exceptions.c文件中,所有内置异常的基类BaseException也在该文件中定义。
核心实现代码片段
/* Exception 类的核心定义简化版本 */ PyTypeObject PyException_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "Exception", sizeof(PyBaseExceptionObject), 0, (destructor)BaseException_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)BaseException_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)BaseException_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ PyDoc_STR("Common base class for all non-exit exceptions."), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyBaseException_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BaseException_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
Exception类完全复用了BaseException的初始化、析构、字符串转换等逻辑,没有单独实现额外的核心方法。
内置默认属性与方法说明
args:异常初始化时传入的参数元组,所有内置异常默认携带该属性__traceback__:异常抛出时自动绑定的回溯对象,可通过traceback标准库模块解析with_traceback(tb):显式设置异常的回溯对象,调用后返回异常实例本身__str__():返回异常的可读字符串表示,默认输出args参数的拼接结果__repr__():返回异常的官方字符串表示,包含异常类名和参数信息__reduce__():实现pickle序列化协议,支持异常对象的序列化操作
内容的提问来源于stack exchange,提问作者Derek1st
相关产品推荐
相关产品推荐

