Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/concurrent/futures/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,10 @@ def add_done_callback(self, fn):
if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
self._done_callbacks.append(fn)
return
fn(self)
try:
fn(self)
except Exception:
LOGGER.exception('exception calling callback for %r', self)

def result(self, timeout=None):
"""Return the result of the call that the future represents.
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_concurrent_futures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,22 @@ def fn(callback_future):
f.add_done_callback(fn)
self.assertTrue(was_cancelled)

def test_done_callback_raises_already_succeeded(self):
with test.support.captured_stderr() as stderr:
def raising_fn(callback_future):
raise Exception('doh!')

f = Future()

# Set the result first to simulate a future that runs instantly,
# effectively allowing the callback to be run immediately.
f.set_result(5)
f.add_done_callback(raising_fn)

self.assertIn('exception calling callback for', stderr.getvalue())
self.assertIn('doh!', stderr.getvalue())


def test_repr(self):
self.assertRegex(repr(PENDING_FUTURE),
'<Future at 0x[0-9a-f]+ state=pending>')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Handle exceptions raised by functions added by concurrent.futures add_done_callback correctly when the Future has already completed.