mirror of
https://github.com/python/cpython.git
synced 2025-07-28 13:44:43 +00:00
[3.10] bpo-44594: fix (Async)ExitStack handling of __context__ (gh-27089) (GH-28730)
Make enter_context(foo()) / enter_async_context(foo()) equivalent to
`[async] with foo()` regarding __context__ when an exception is raised.
Previously exceptions would be caught and re-raised with the wrong
context when explicitly overriding __context__ with None..
(cherry picked from commit e6d1aa1ac6
)
Co-authored-by: John Belmonte <john@neggie.net>
Automerge-Triggered-By: GH:njsmith
This commit is contained in:
parent
1e328afb04
commit
872b1e537e
4 changed files with 76 additions and 4 deletions
|
@ -552,6 +552,41 @@ class TestAsyncExitStack(TestBaseExitStack, unittest.TestCase):
|
|||
self.assertIsInstance(inner_exc, ValueError)
|
||||
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
|
||||
|
||||
@_async_test
|
||||
async def test_async_exit_exception_explicit_none_context(self):
|
||||
# Ensure AsyncExitStack chaining matches actual nested `with` statements
|
||||
# regarding explicit __context__ = None.
|
||||
|
||||
class MyException(Exception):
|
||||
pass
|
||||
|
||||
@asynccontextmanager
|
||||
async def my_cm():
|
||||
try:
|
||||
yield
|
||||
except BaseException:
|
||||
exc = MyException()
|
||||
try:
|
||||
raise exc
|
||||
finally:
|
||||
exc.__context__ = None
|
||||
|
||||
@asynccontextmanager
|
||||
async def my_cm_with_exit_stack():
|
||||
async with self.exit_stack() as stack:
|
||||
await stack.enter_async_context(my_cm())
|
||||
yield stack
|
||||
|
||||
for cm in (my_cm, my_cm_with_exit_stack):
|
||||
with self.subTest():
|
||||
try:
|
||||
async with cm():
|
||||
raise IndexError()
|
||||
except MyException as exc:
|
||||
self.assertIsNone(exc.__context__)
|
||||
else:
|
||||
self.fail("Expected IndexError, but no exception was raised")
|
||||
|
||||
|
||||
class TestAsyncNullcontext(unittest.TestCase):
|
||||
@_async_test
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue