Commit b35acc5b authored by Romain Picard's avatar Romain Picard Committed by Miss Islington (bot)

bpo-35125: remove inner callback on outer cancellation in asyncio shield (GH-10340)



When the future returned by shield is cancelled, its completion callback of the
inner future is not removed. This makes the callback list of inner inner future
grow each time a shield is created and cancelled.

This change unregisters the callback from the inner future when the outer
future is cancelled.



https://bugs.python.org/issue35125
parent f7bda5c5
...@@ -818,7 +818,7 @@ def shield(arg, *, loop=None): ...@@ -818,7 +818,7 @@ def shield(arg, *, loop=None):
loop = futures._get_loop(inner) loop = futures._get_loop(inner)
outer = loop.create_future() outer = loop.create_future()
def _done_callback(inner): def _inner_done_callback(inner):
if outer.cancelled(): if outer.cancelled():
if not inner.cancelled(): if not inner.cancelled():
# Mark inner's result as retrieved. # Mark inner's result as retrieved.
...@@ -834,7 +834,13 @@ def shield(arg, *, loop=None): ...@@ -834,7 +834,13 @@ def shield(arg, *, loop=None):
else: else:
outer.set_result(inner.result()) outer.set_result(inner.result())
inner.add_done_callback(_done_callback)
def _outer_done_callback(outer):
if not inner.done():
inner.remove_done_callback(_inner_done_callback)
inner.add_done_callback(_inner_done_callback)
outer.add_done_callback(_outer_done_callback)
return outer return outer
......
...@@ -1777,7 +1777,7 @@ class BaseTaskTests: ...@@ -1777,7 +1777,7 @@ class BaseTaskTests:
test_utils.run_briefly(self.loop) test_utils.run_briefly(self.loop)
self.assertIs(outer.exception(), exc) self.assertIs(outer.exception(), exc)
def test_shield_cancel(self): def test_shield_cancel_inner(self):
inner = self.new_future(self.loop) inner = self.new_future(self.loop)
outer = asyncio.shield(inner) outer = asyncio.shield(inner)
test_utils.run_briefly(self.loop) test_utils.run_briefly(self.loop)
...@@ -1785,6 +1785,15 @@ class BaseTaskTests: ...@@ -1785,6 +1785,15 @@ class BaseTaskTests:
test_utils.run_briefly(self.loop) test_utils.run_briefly(self.loop)
self.assertTrue(outer.cancelled()) self.assertTrue(outer.cancelled())
def test_shield_cancel_outer(self):
inner = self.new_future(self.loop)
outer = asyncio.shield(inner)
test_utils.run_briefly(self.loop)
outer.cancel()
test_utils.run_briefly(self.loop)
self.assertTrue(outer.cancelled())
self.assertEqual(0, 0 if outer._callbacks is None else len(outer._callbacks))
def test_shield_shortcut(self): def test_shield_shortcut(self):
fut = self.new_future(self.loop) fut = self.new_future(self.loop)
fut.set_result(42) fut.set_result(42)
......
Asyncio: Remove inner callback on outer cancellation in shield
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment