【问题标题】:How to determine which attribute an AttributeError refers to?如何确定 AttributeError 指的是哪个属性?
【发布时间】:2017-04-05 00:15:05
【问题描述】:

当我请求一个不存在的 python 对象的属性时,我得到一个 AttributeError,但是我没有在错误对象的字段中找到请求的属性的名称。唯一提到请求属性名称的地方是错误的args 成员。

在我看来,解析错误消息以获取缺失属性的名称有点烦人。有什么方法可以在不解析错误信息的情况下获取缺失属性的名称?

演示:

class A:
    def f(self):
        print('in A')


class B:
    pass


class C:
    def f(self):
        print('in C')
        raise AttributeError()


def call_f(o):
    try:
        o.f()
    except AttributeError as e:
        # instead of e.args[0].endswith("'f'") it would be nice to do
        # e.missing_attribute == 'f'
        if e.args and e.args[0].endswith("'f'"):
            print(e.args) # prints ("'B' object has no attribute 'f'",)
        else: raise

if __name__ == '__main__':
    a = A()
    b = B()
    c = C()

    call_f(a)
    call_f(b)
    call_f(c)

【问题讨论】:

  • 不,没有。为什么您不知道您要访问的属性是什么?即使您使用例如动态地进行操作getattr,你有 name 参数。
  • @jonrsharpe 如果hi 未在a 中定义,我想做的是抑制错误。另一方面,如果hi is 在 a 中定义,那么它可能会在内部引发 AttributeError,在这种情况下,我想进一步传播这个错误(在我的 except 块中重新引发)。
  • 如果定义了,就不会报错。能否给出一个具体的用例?
  • @jonrsharpe 如果定义了hi 并且它会抛出 AttributeError 本身(在它的主体中),那么就无法区分 AttributeError 是否是由于缺少hi 或由于缺少 hi 内部所需的其他内容。我需要解析错误中的错误消息才能理解它。这是一个演示:pastebin.com/wxss4b8XThe
  • 我的意思是你实际上试图解决的问题,而不是那么做作的东西。但你有一个你喜欢的答案,所以没关系。

标签: python exception error-handling standard-library anti-patterns


【解决方案1】:

目前没有统一的方法来做到这一点。该功能已在PEP 473 中提出 还在草稿中

【讨论】:

  • @anton 你有,它说 "AttributeError : target , attribute"
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-20
相关资源
最近更新 更多