从消息模板创建异常类。
exception-template的Python项目详细描述
在避免锅炉板的情况下,使用一致的消息引发异常。
比较这个:
>>> from exception_template import ExceptionTemplate >>> class MyException(ExceptionTemplate): ... message = 'Hello, {person}. Here is my {adjective} exception class.' >>> raise MyException(person='Ryan', adjective='fancy') Traceback (most recent call last): ... MyException: Hello, Ryan. Here is my fancy exception class.
对此:
>>> class MyException(Exception): ... def __init__(self, person: str, adjective: str) -> None: ... self.person = person ... self.adjective = adjective ... super().__init__('Hello, {person}. Here is my {adjective} exception class.' ... .format(person=person, adjective=adjective)) >>> raise MyException('Ryan', 'lame') Traceback (most recent call last): ... MyException: Hello, Ryan. Here is my lame exception class.
或者这个:
>>> class MyException(Exception): ... pass >>> raise MyException('Hello, Ryan. Here is my exception class with a message I copy-pasted in 500 places.') Traceback (most recent call last): ... MyException: Hello, Ryan. Here is my exception class with a message I copy-pasted in 500 places.
此外,exceptionTemplate参数作为异常实例的成员可用:
>>> try: ... foo() ... except MyException as ex: ... print(ex.person) Ryan
安装
pip install exception-template
不需要额外的依赖关系!