@@ -274,17 +274,17 @@ def __init__(
274
274
self ._tasks = set ()
275
275
276
276
async def __aenter__ (self ) -> Client :
277
- if self .loop is MISSING :
277
+ if self ._loop is MISSING :
278
278
try :
279
- self .loop = asyncio .get_running_loop ()
279
+ self ._loop = asyncio .get_running_loop ()
280
280
except RuntimeError :
281
281
# No event loop was found, this should not happen
282
282
# because entering on this context manager means a
283
283
# loop is already active, but we need to handle it
284
284
# anyways just to prevent future errors.
285
285
286
286
# Maybe handle different system event loop policies?
287
- self .loop = asyncio .new_event_loop ()
287
+ self ._loop = asyncio .new_event_loop ()
288
288
289
289
self .http .loop = self .loop
290
290
self ._connection .loop = self .loop
@@ -822,10 +822,12 @@ async def runner():
822
822
async with self :
823
823
await self .start (token = token , reconnect = reconnect )
824
824
825
- run = asyncio .run
826
-
827
- if self .loop is not MISSING :
825
+ try :
828
826
run = self .loop .run_until_complete
827
+ requires_cleanup = True
828
+ except RuntimeError :
829
+ run = asyncio .run
830
+ requires_cleanup = False
829
831
830
832
try :
831
833
run (runner ())
@@ -834,8 +836,11 @@ async def runner():
834
836
if not self .is_closed ():
835
837
self .loop .run_until_complete (self .close ())
836
838
837
- _log .info ("Cleaning up tasks." )
838
- _cleanup_loop (self .loop )
839
+ # asyncio.run automatically does the cleanup tasks, so if we use
840
+ # it we don't need to clean up the tasks.
841
+ if requires_cleanup :
842
+ _log .info ("Cleaning up tasks." )
843
+ _cleanup_loop (self .loop )
839
844
840
845
# properties
841
846
0 commit comments