@@ -181,13 +181,19 @@ def _interleave_addrinfos(addrinfos, first_address_family_count=1):
181181 return reordered
182182
183183
184+ _run_until_complete_running = contextvars .ContextVar (
185+ '_run_until_complete_running' , default = True )
186+
187+
184188def _run_until_complete_cb (fut ):
185189 if not fut .cancelled ():
186190 exc = fut .exception ()
187191 if isinstance (exc , (SystemExit , KeyboardInterrupt )):
188192 # Issue #22429: run_forever() already finished, no need to
189193 # stop it.
190194 return
195+ if not _run_until_complete_running .get ():
196+ return
191197 futures ._get_loop (fut ).stop ()
192198
193199
@@ -709,17 +715,10 @@ def run_until_complete(self, future):
709715
710716 # gh-158406: A queued callback can outlive this call. Only let
711717 # it stop the loop while this call is running.
712- running = True
713-
714- def done_cb (fut ):
715- if running :
716- _run_until_complete_cb (fut )
717- elif not fut .cancelled ():
718- # Still mark the exception as retrieved.
719- fut .exception ()
720-
718+ context = contextvars .copy_context ()
719+ context .run (_run_until_complete_running .set , True )
721720 try :
722- future .add_done_callback (done_cb )
721+ future .add_done_callback (_run_until_complete_cb , context = context )
723722 self .run_forever ()
724723 except :
725724 if new_task and future .done () and not future .cancelled ():
@@ -729,8 +728,8 @@ def done_cb(fut):
729728 future .exception ()
730729 raise
731730 finally :
732- running = False
733- future .remove_done_callback (done_cb )
731+ context . run ( _run_until_complete_running . set , False )
732+ future .remove_done_callback (_run_until_complete_cb )
734733 if not future .done ():
735734 raise RuntimeError ('Event loop stopped before Future completed.' )
736735
0 commit comments