Exception definitions in Python are not great. There are two main ways they're used in the code that I've read:
1) By far the most common: >>> class MyException(Exception): ... pass >>> raise MyException(f'Bad thing happened during {action} in {context}') 2) Much rarer: >>> class MyException(Exception): ... def __init__(self, action, context): ... super().__init__(f'Bad thing happened during {action} in {context}') >>> raise MyException(current_action, current_context) Version 1 is quick and easy, but messages skew and become inconsistent as they're copied from place to place. The Python standard library isn't immune to this either. Version 2 looks simple enough to do, but all of the repetitious boilerplate adds up when several exception types need to be defined. (And it's even worse when you want all of your code to include typing annotations.) Most people don't bother. My proposal is a new exception class as the preferred base for user-defined exceptions: >>> class MyException(ExceptionTemplate): ... message = 'Bad thing happened during {action} in {context}' >>> raise MyException(action=current_action, context=current_context) I have a reference implementation, implemented in an almost trivial amount of pure Python code: https://github.com/rcfox/exception-template/blob/master/exception_template/exception_template.py So why am I bothering you with this? I would like to see this become the preferred method of defining new exceptions as recommended by the Python documentation. This would also require adding ExceptionTemplate as a built-in exception type. I will grant that ExceptionTemplate seems a little bit magical, but all of the required arguments are explicitly laid out to the user in the 'message' field, and format strings should be a familiar concept to most users. I've also included some tests that show that you can still treat these exceptions as regular classes: https://github.com/rcfox/exception-template/blob/master/tests/test.py#L53
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/GEO2WZQQJ6HMSXZIRFCKTRM7TYFQXNZ2/ Code of Conduct: http://python.org/psf/codeofconduct/