Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing Warning

I am building an application with "never fail (unless absolutely must)" philosophy. Non-fatal errors will be collected and presented to end user as warnings in a report. Subclassing Warning class seems to be a good idea, but there is one very strange obstacle: I can only issue warnings using the following library method:

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

So let's say one of the warnings I need to log is about 99 misspellings in a text document, along with line number where each misspelling occurred:

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

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

...a document has been processed and a UserCannotSpell() object is prepared. The only problem: I cannot raise it nor can I warnings.warn() it. Any suggestions?

like image 460
Muposat Avatar asked Jan 18 '26 22:01

Muposat


1 Answers

Thanks to @BrenBarn for pointing out that message can be an object. This way subclassing of Warning looks rather ugly but at least it is usable:

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)

Output:

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

>>> w[0].message.custom_data
33
like image 174
Muposat Avatar answered Jan 20 '26 13:01

Muposat