🔴 python -OO
As the reference states, -OO
mode will discard the docstrings.
python -OO script.py
examples/wizardry.py
from dataclasses import dataclass
from documented import DocumentedError
@dataclass # (1)!
class InsufficientWizardryLevel(DocumentedError):
"""
🧙 Your level of wizardry is insufficient ☹
Spell: {self.spell}
Minimum level required: {self.required_level}
Actual level: {self.actual_level} {self.comment}
Unseen University will be happy to assist in your training! 🎓
""" # (2)!
spell: str
required_level: int
actual_level: int
@property # (3)!
def comment(self) -> str:
if self.actual_level <= 0:
return '(You are Rincewind, right? Hi!)'
else:
return ''
raise InsufficientWizardryLevel(
spell='Animal transformation',
required_level=8,
actual_level=0,
)
-
Usage of
dataclasses
is not required but helps alleviate boilerplate. -
Docstring is used to render the exception. More than that, you can render fields of the exception instance in it using
{self.something}
placeholders. -
You cannot call methods of the exception instance. But you can refer to properties to help generate dynamic content.
python
Traceback (most recent call last):
File "📂/wizardry.py", line 29, in <module>
raise InsufficientWizardryLevel(
InsufficientWizardryLevel: InsufficientWizardryLevel(spell: str, required_level: int, actual_level: int)
As you can see, the Fallback __repr__
mode is used in this case.