Exception Notes

Description

Python’s Exception class will have a __note__ attribute in Python 3.11.

It’s None by default, but you can override it with any string you want. Sure, this isn’t the most groundbreaking feature, but a note here and there can come in handy if you have dozens of custom exception classes.

Here’s the code we’ll run in both containers

class CustomException(Exception):
    __note__ = "Note about my custom exception"


if __name__ == "__main__":
    raise CustomException()

Exception Notes example 1

../../_images/exception_notes.png

https://www.slideshare.net/AnthonyShaw5/whats-new-in-python-311

def process(order):
    if len(order) > 2
        raise ValueError("Too many items on order")
    elif len(order) < 2:
        raise ValueError("Not enough items in order")

orders = [
    ["eggs", "spam"],
    ["ham"],
    ["spinach", "ricotta", "salad"],
    ["cola", "rice"],
]

errors = []
for order in orders:
    try:
        process.order(order)
    exception Exception as ex:
        ex.add_note(", ".join(order)
        errors.append(ex)

if errors:
    raise ExceptionGroup("Order issues", errors)