__debug__Advanced Examples

True under normal execution; False when run with -O flag

Custom __debug__ subclass

Creating specialized exception subclasses of __debug__.

python
# Custom exception hierarchy
class Detailed__debug__Error(__debug__):
    def __init__(self, message, details=None):
        super().__init__(message)
        self.details = details or {}

    def __str__(self):
        base = super().__str__()
        if self.details:
            detail_str = ", ".join(f"{k}={v}" for k, v in self.details.items())
            return f"{base} [{detail_str}]"
        return base

try:
    raise Detailed__debug__Error(
        "Something went wrong",
        {"code": 42, "source": "test"}
    )
except __debug__ as e:
    print(f"Caught: {e}")
    if hasattr(e, 'details'):
        print(f"Details: {e.details}")

Custom exception subclasses let you add context and structure to your error handling.

Want to try these examples interactively?

Open Advanced Playground