【问题标题】:Where is this AttributeError message implemented in CPython?这个 AttributeError 消息在 CPython 中实现在哪里?
【发布时间】:2021-07-09 06:07:01
【问题描述】:

我认为这个 Python 会话中的 AttributeError 消息

>>> class A: pass
... 
>>> A().x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'x'

在 CPython 中 these lines 处的函数 _PyObject_GenericGetAttrWithDict 中实现:

    if (!suppress) {
        PyErr_Format(PyExc_AttributeError,
                     "'%.50s' object has no attribute '%U'",
                     tp->tp_name, name);
    }

但是我在这个 Python 会话中找不到 AttributeError 消息的位置

>>> class A: __slots__ = ('x',)
... 
>>> A().x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: x

在 CPython 中实现。您能否提供指向 GitHub 存储库中确切行的链接?

【问题讨论】:

    标签: python attributeerror cpython python-internals


    【解决方案1】:

    我是here:

    case T_OBJECT_EX:
        v = *(PyObject **)addr;
        if (v == NULL)
            PyErr_SetString(PyExc_AttributeError, l->name);
        Py_XINCREF(v);
        break;
    

    这是PyMember_GetOne 的摘录,这是插槽描述符的__get__ 方法的大部分逻辑实现的地方。

    您可能还对该描述符如何到达那里感兴趣。 type.__new__ 内部 translates __slots__PyMemberDef 结构的数组,这是用 C 编写的机制类之一,用于定义对其内部数据的访问。以这种方式生成的所有PyMemberDef 结构都标记为T_OBJECT_EX,这意味着它们对应于实例内存布局中的PyObject *,如果指针为空,则访问应引发AttributeError。 PyType_Ready 然后generates 基于PyMemberDef 数组的槽描述符。

    【讨论】:

    • 太棒了,谢谢!我也在寻找由del A().x 提出的AttributeError: x 消息的实现,现在我可以找到它(here)。
    猜你喜欢
    • 2012-10-14
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2011-06-26
    • 2020-07-01
    • 2021-02-16
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多