子类警告

时间:2015-01-23 20:30:48

标签: python warnings

我正在使用&#34建立一个应用程序;永远不会失败(除非绝对必须)"哲学。将收集非致命错误并将其作为报告中的警告呈现给最终用户。子类化警告类似乎是一个好主意,但有一个非常奇怪的障碍:我只能使用以下库方法发出警告:

warnings.warn(message, category=None, stacklevel=1)`

所以,让我们说我需要记录的警告之一是文本文档中的99个拼写错误,以及每个拼写错误发生的行号:

class UserCannotSpell(UserWarning):
    def __init__(self, misspelled_document):
        super().__init__()
        self.document = misspelled_document
        self.misspellings = []

    def add(self, misspelling):
        self.misspellings.append(misspelling)

...已处理文档并准备了UserCannotSpell()个对象。唯一的问题是:我不能raise它也不能warnings.warn()它。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

感谢@BrenBarn指出该消息可以是一个对象。这种方式的子类化警告看起来相当丑陋,但至少它是可用的:

with warnings.catch_warnings(record=True) as w:
    warning_obj = UserCannotSpell('Houston, we have a problem')
    warning_obj.custom_data = 33
    warnings.warn(warning_obj)

输出:

>>> w
[<warnings.WarningMessage object at 0x02E011F0>]

>>> w[0].message.custom_data
33