Record `__cause__` and `__context__` on exceptions

Merged
SA
1mo ago
+650-62

Implements raise X from Y and exception chaining attributes.

raise X from Y compiles to a new RaiseFrom opcode (appended, so no DUMP_VERSION bump).
The cause may be None, an exception instance or an exception class, which is instantiated; anything else raises TypeError: exception causes must derive from BaseException.
It is stored as __cause__ and sets __suppress_context__ = True.

An exception raised while another is being handled records the handled one as __context__, cutting a link that would form a loop, as CPython does.
__cause__, __context__ and __suppress_context__ are readable on every exception.

The chain lives on the heap object only.
Copies of an exception travelling inside a RunError are rebuilt without one, so a chain is lost when an exception crosses a nested synchronous call (for example out of a sorted(key=...) callback).
Exceptions remain GC leaves, so a cause cycle built by hand leaks until the session ends.
Chained tracebacks (The above exception was the direct cause...) are not rendered.
All of this is recorded in limitations/exceptions.md.

Tests in exception__chaining.py.
Part of the set of PRs for the stdlib gaps reported by a user running Monty as an agent code-mode sandbox.

šŸ¤– Generated with Claude Code

https://claude.ai/code/session_018zfZ5wd33kjDtV7BoUUV2T


Summary by cubic

Implements raise X from Y and the exception chaining attributes __cause__, __context__, and __suppress_context__. Previously from Y was silently dropped and these attributes did not exist.

  • raise X from Y sets __cause__ and __suppress_context__; causes may be None, an exception, or an exception class (instantiated). Invalid causes raise TypeError, checking the exception before the cause like CPython.
  • Exceptions raised while another is handled record it as __context__, cutting loops; the scan polls the clock so the time limit can end it. A popped frame drops its open handlers, so a finished handler's exception is not attached, and exceptions from internal (frozen) handlers are skipped, so functools.reduce's TypeError chains like CPython's. An __exit__ raising inside a with keeps the body's exception as context, matching CPython, so the corresponding with limitation was dropped.
  • The attributes are read-only; assignment raises AttributeError.
  • Added a RaiseFrom opcode (appended, no dump version bump).
  • Freeing an exception releases its chained __cause__/__context__ references so a chain does not outlive it, and the reachability walk follows chains so retained chains are not reported as leaked; a manually-built cause cycle still leaks until the session ends because exceptions are not cycle-collected.
  • The chain lives on the heap object only and is lost when an exception is rebuilt from a copy (e.g., after crossing a nested synchronous call like a sorted() key).
  • Chained tracebacks are not rendered.