Skip to content

Commit a176574

Browse files
committed
Always create the exceptions tuple at init and return it from the exceptions property
Fixes #143.
1 parent 550b796 commit a176574

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

CHANGES.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
1414
- Changed ``BaseExceptionGroup.__init__()`` to directly call
1515
``BaseException.__init__()`` instead of the superclass ``__init__()`` in order to
1616
emulate the CPython behavior (broken or not) (PR by @cfbolz)
17+
- Changed the ``exceptions`` attribute to always return the same tuple of exceptions,
18+
created from the original exceptions sequence passed to ``BaseExceptionGroup`` to
19+
match CPython behavior
20+
(`#143 <https://github.com/agronholm/exceptiongroup/issues/143>`_)
1721

1822
**1.2.2**
1923

src/exceptiongroup/_exceptions.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,7 @@ def __new__(
101101
)
102102

103103
instance = super().__new__(cls, __message, __exceptions)
104-
instance._message = __message
105-
instance._exceptions = __exceptions
104+
instance._exceptions = tuple(__exceptions)
106105
return instance
107106

108107
def __init__(
@@ -126,7 +125,7 @@ def add_note(self, note: str) -> None:
126125

127126
@property
128127
def message(self) -> str:
129-
return self._message
128+
return self.args[0]
130129

131130
@property
132131
def exceptions(
@@ -276,7 +275,7 @@ def __str__(self) -> str:
276275
return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})"
277276

278277
def __repr__(self) -> str:
279-
return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})"
278+
return f"{self.__class__.__name__}({self.args[0]!r}, {self.args[1]!r})"
280279

281280

282281
class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception):

tests/test_exceptions.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,3 +864,18 @@ class MyExceptionGroup(base, MyException):
864864
MyExceptionGroup(
865865
"...", [Exception()]
866866
) # does not try to call MyException.__init__
867+
868+
869+
def test_exceptions_mutate_original_sequence():
870+
exceptions = [ValueError(1), KeyboardInterrupt()]
871+
excgrp = BaseExceptionGroup("foo", exceptions)
872+
exc_tuple = excgrp.exceptions
873+
assert isinstance(exc_tuple, tuple)
874+
assert list(exc_tuple) == exceptions
875+
876+
exceptions.append(KeyError("bar"))
877+
assert excgrp.exceptions is exc_tuple
878+
assert repr(excgrp) == (
879+
"BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt(), "
880+
"KeyError('bar')])"
881+
)

0 commit comments

Comments
 (0)