Repository: agronholm/exceptiongroup

Issue:
Bizarre error in `sys.excepthook` with recursive calls
```python-traceback
Error in sys.excepthook:
Traceback (most recent call last):
  File "/root/.pyenv/versions/3.10.4/lib/python3.10/site-packages/exceptiongroup/_formatting.py", line 71, in exceptiongroup_excepthook
    sys.stderr.write("".join(traceback.format_exception(etype, value, tb)))
  File "/root/.pyenv/versions/3.10.4/lib/python3.10/traceback.py", line 136, in format_exception
    return list(te.format(chain=chain))
  File "/root/.pyenv/versions/3.10.4/lib/python3.10/site-packages/exceptiongroup/_formatting.py", line 206, in format
    yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx)
  File "/root/.pyenv/versions/3.10.4/lib/python3.10/site-packages/exceptiongroup/_formatting.py", line 142, in format
    if exc.__cause__ is not None:
AttributeError: 'PatchedTracebackException' object has no attribute '__cause__'. Did you mean: '__class__'?
```

I'm pretty sure this is because [the upstream `__init__` method doesn't assign `__cause__` for recursive calls](https://github.com/python/cpython/blob/dddbbd9e3e4e12ed5a805dd4e08953e3332a15ea/Lib/traceback.py#L525-L567), and so if you happen to hit this (on `exceptiongroup == 1.0.0rc9`) you subsequently crash with an AttributeError.  

I think the obvious `getattr(exc, "__cause__", None)` patch is probably the best way forward; happy to write that if you'd like.  Unfortunately I don't have a good reproducing case or indeed any way to reproduce this locally - it's consistently crashing _only_ in a particular build and CI system, and at time of writing I've worked out why but not constructed a repro.

Discussion:
coveralls: ## Pull Request Test Coverage Report for [Build 3332981553](https://coveralls.io/builds/53641944)

* **0** of **0**   changed or added relevant lines in **0** files are covered.
* **203** unchanged lines in **6** files lost coverage.
* Overall coverage decreased (**-0.08%**) to **74.524%**

---


|  Files with Coverage Reduction | New Missed Lines | % |
| :-----|--------------|--: |
| [/opt/hostedtoolcache/Python/3.10.8/x64/lib/python3.10/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPython%2F3.10.8%2Fx64%2Flib%2Fpython3.10%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L140) | 15 | 90.4% |
| [/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPython%2F3.7.15%2Fx64%2Flib%2Fpython3.7%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L140) | 15 | 89.8% |
| [/opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPython%2F3.8.14%2Fx64%2Flib%2Fpython3.8%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L140) | 15 | 89.9% |
| [/opt/hostedtoolcache/Python/3.9.15/x64/lib/python3.9/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPython%2F3.9.15%2Fx64%2Flib%2Fpython3.9%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L140) | 15 | 89.9% |
| [/opt/hostedtoolcache/PyPy/3.8.13/x64/lib/pypy3.8/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPyPy%2F3.8.13%2Fx64%2Flib%2Fpypy3.8%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L91) | 67 | 23.23% |
| [/opt/hostedtoolcache/Python/3.11.0/x64/lib/python3.11/site-packages/exceptiongroup/_formatting.py](https://coveralls.io/builds/53641944/source?filename=%2Fopt%2Fhostedtoolcache%2FPython%2F3.11.0%2Fx64%2Flib%2Fpython3.11%2Fsite-packages%2Fexceptiongroup%2F_formatting.py#L91) | 76 | 0% |
<!-- | **Total:** | **203** |  | -->

|  Totals | [![Coverage Status](https://coveralls.io/builds/53641944/badge)](https://coveralls.io/builds/53641944) |
| :-- | --: |
| Change from base [Build 3324050034](https://coveralls.io/builds/53598819): |  -0.08% |
| Covered Lines: | 1799 |
| Relevant Lines: | 2414 |

---
##### 💛  - [Coveralls](https://coveralls.io)


Patch:
diff --git a/CHANGES.rst b/CHANGES.rst
index 0c11a2c..8a847a8 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -3,6 +3,16 @@ Version history
 
 This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
 
+**UNRELEASED**
+
+- Fixed
+  ``AttributeError: 'PatchedTracebackException' object has no attribute '__cause__'``
+  on Python 3.10 (only) when a traceback is printed from an exception where an exception
+  group is set as the cause (#33)
+- Fixed a loop in exception groups being rendered incorrectly (#35)
+- Fixed the patched formatting functions (``format_exception()``etc.) not passing the
+  ``compact=True`` flag on Python 3.10 like the original functions do
+
 **1.0.0rc9**
 
 - Added custom versions of several ``traceback``  functions that work with exception
diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py
index 2c74162..0bffd91 100644
--- a/src/exceptiongroup/_formatting.py
+++ b/src/exceptiongroup/_formatting.py
@@ -76,7 +76,7 @@ class PatchedTracebackException(traceback.TracebackException):
         self,
         exc_type: type[BaseException],
         exc_value: BaseException,
-        exc_traceback: TracebackType,
+        exc_traceback: TracebackType | None,
         *,
         limit: int | None = None,
         lookup_lines: bool = True,
@@ -88,8 +88,6 @@ class PatchedTracebackException(traceback.TracebackException):
         if sys.version_info >= (3, 10):
             kwargs["compact"] = compact
 
-        # Capture the original exception and its cause and context as
-        # TracebackExceptions
         traceback_exception_original_init(
             self,
             exc_type,
@@ -102,33 +100,82 @@ class PatchedTracebackException(traceback.TracebackException):
             **kwargs,
         )
 
-        seen_was_none = _seen is None
-
+        is_recursive_call = _seen is not None
         if _seen is None:
             _seen = set()
+        _seen.add(id(exc_value))
+
+        # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
+        # queue to avoid recursion (only the top-level call gets _seen == None)
+        if not is_recursive_call:
+            queue = [(self, exc_value)]
+            while queue:
+                te, e = queue.pop()
+
+                if e and e.__cause__ is not None and id(e.__cause__) not in _seen:
+                    cause = PatchedTracebackException(
+                        type(e.__cause__),
+                        e.__cause__,
+                        e.__cause__.__traceback__,
+                        limit=limit,
+                        lookup_lines=lookup_lines,
+                        capture_locals=capture_locals,
+                        _seen=_seen,
+                    )
+                else:
+                    cause = None
 
-        # Capture each of the exceptions in the ExceptionGroup along with each of
-        # their causes and contexts
-        if isinstance(exc_value, BaseExceptionGroup):
-            embedded = []
-            for exc in exc_value.exceptions:
-                if id(exc) not in _seen:
-                    embedded.append(
-                        PatchedTracebackException(
+                if compact:
+                    need_context = (
+                        cause is None and e is not None and not e.__suppress_context__
+                    )
+                else:
+                    need_context = True
+                if (
+                    e
+                    and e.__context__ is not None
+                    and need_context
+                    and id(e.__context__) not in _seen
+                ):
+                    context = PatchedTracebackException(
+                        type(e.__context__),
+                        e.__context__,
+                        e.__context__.__traceback__,
+                        limit=limit,
+                        lookup_lines=lookup_lines,
+                        capture_locals=capture_locals,
+                        _seen=_seen,
+                    )
+                else:
+                    context = None
+
+                # Capture each of the exceptions in the ExceptionGroup along with each
+                # of their causes and contexts
+                if e and isinstance(e, BaseExceptionGroup):
+                    exceptions = []
+                    for exc in e.exceptions:
+                        texc = PatchedTracebackException(
                             type(exc),
                             exc,
                             exc.__traceback__,
                             lookup_lines=lookup_lines,
                             capture_locals=capture_locals,
-                            # copy the set of _seen exceptions so that duplicates
-                            # shared between sub-exceptions are not omitted
-                            _seen=None if seen_was_none else set(_seen),
+                            _seen=_seen,
                         )
-                    )
-            self.exceptions = embedded
-            self.msg = exc_value.message
-        else:
-            self.exceptions = None
+                        exceptions.append(texc)
+                else:
+                    exceptions = None
+
+                te.__cause__ = cause
+                te.__context__ = context
+                te.exceptions = exceptions
+                if cause:
+                    queue.append((te.__cause__, e.__cause__))
+                if context:
+                    queue.append((te.__context__, e.__context__))
+                if exceptions:
+                    queue.extend(zip(te.exceptions, e.exceptions))
+
         self.__notes__ = getattr(exc_value, "__notes__", ())
 
     def format(self, *, chain=True, _ctx=None):
@@ -280,7 +327,9 @@ if sys.excepthook is sys.__excepthook__:
 @singledispatch
 def format_exception_only(__exc: BaseException) -> List[str]:
     return list(
-        PatchedTracebackException(type(__exc), __exc, None).format_exception_only()
+        PatchedTracebackException(
+            type(__exc), __exc, None, compact=True
+        ).format_exception_only()
     )
 
 
@@ -297,7 +346,7 @@ def format_exception(
 ) -> List[str]:
     return list(
         PatchedTracebackException(
-            type(__exc), __exc, __exc.__traceback__, limit=limit
+            type(__exc), __exc, __exc.__traceback__, limit=limit, compact=True
         ).format(chain=chain)
     )
 


Test patch:
diff --git a/tests/test_formatting.py b/tests/test_formatting.py
index 0270cb9..7cfc152 100644
--- a/tests/test_formatting.py
+++ b/tests/test_formatting.py
@@ -88,6 +88,70 @@ def test_exceptionhook(capsys: CaptureFixture) -> None:
     )
 
 
+def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None:
+    try:
+        raise Exception() from ExceptionGroup("", (Exception(),))
+    except Exception as exc:
+        sys.excepthook(type(exc), exc, exc.__traceback__)
+
+    lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno
+    module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
+    output = capsys.readouterr().err
+    assert output == (
+        f"""\
+  | {module_prefix}ExceptionGroup:  (1 sub-exception)
+  +-+---------------- 1 ----------------
+    | Exception
+    +------------------------------------
+
+The above exception was the direct cause of the following exception:
+
+Traceback (most recent call last):
+  File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause
+    raise Exception() from ExceptionGroup("", (Exception(),))
+Exception
+"""
+    )
+
+
+def test_exceptiongroup_loop(capsys: CaptureFixture) -> None:
+    e0 = Exception("e0")
+    eg0 = ExceptionGroup("eg0", (e0,))
+    eg1 = ExceptionGroup("eg1", (eg0,))
+
+    try:
+        raise eg0 from eg1
+    except ExceptionGroup as exc:
+        sys.excepthook(type(exc), exc, exc.__traceback__)
+
+    lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6
+    module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
+    output = capsys.readouterr().err
+    assert output == (
+        f"""\
+  | {module_prefix}ExceptionGroup: eg1 (1 sub-exception)
+  +-+---------------- 1 ----------------
+    | Exception Group Traceback (most recent call last):
+    |   File "{__file__}", line {lineno}, in test_exceptiongroup_loop
+    |     raise eg0 from eg1
+    | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
+    +-+---------------- 1 ----------------
+      | Exception: e0
+      +------------------------------------
+
+The above exception was the direct cause of the following exception:
+
+  + Exception Group Traceback (most recent call last):
+  |   File "{__file__}", line {lineno}, in test_exceptiongroup_loop
+  |     raise eg0 from eg1
+  | {module_prefix}ExceptionGroup: eg0 (1 sub-exception)
+  +-+---------------- 1 ----------------
+    | Exception: e0
+    +------------------------------------
+"""
+    )
+
+
 def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None:
     try:
         raise_excgroup()