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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With