Introduction
Python 3.11 introduced the Exception.add_note() method, which allows attaching additional context notes to exceptions. These notes are displayed in the exception traceback, helping developers debug issues more easily.
Pywikibot currently needs to support older Python versions (< 3.11). To provide similar functionality, we want to backport add_note() method for all exceptions.Error classes.
Goal
Refactor pywikibot.exceptions.Error of the exceptions module to derive from a new BaseError instead of the built-in Exception. For Python < 3.11, BaseError should implement Python 3.11-style Exception.add_note() functionality within backports module.
Steps
- Create a new class BaseError in the backports module
- Derive BaseError from Exception.
- For Python < 3.11 (tools.PYTHON_VERSION < (3, 11)):
- Implement add_note(self, note: str) storing notes in an instance attribute self.__notes__.
- Override __str__() so that super().__str__() is followed by each note on a new line.
- Import BaseError from backports as _BaseError in the in exceptions module (_BaseError to keep the class private). Make pywikibot.exceptions.Error inherit from _BaseError instead of Exception.
- Example usage:
>>> try:
>>> 1/0
>>> except pywikibot.exceptions.Error as e:
>>> e.add_note('omg!')
>>> e.add_note('does it work?')
>>> raise
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
omg!
does it work?Further help
- https://doc.wikimedia.org/pywikibot/master/index.html
- T407059
- https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Pywikibot/Development
- https://www.mediawiki.org/wiki/Manual:Coding_conventions/Python
- https://www.mediawiki.org/wiki/Manual:Pywikibot/Development/Guidelines
- https://docs.python.org/3.15/library/exceptions.html#BaseException
Hint
pre-commit is strictly recommended before submitting a patch. Install it with pip install pre-commit and run it with pre-commit run --all-files