Skip to content

Commit cb05d05

Browse files
committed
chore: make cleanup be done only when necessary
1 parent 0bc5014 commit cb05d05

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

discord/client.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -274,17 +274,17 @@ def __init__(
274274
self._tasks = set()
275275

276276
async def __aenter__(self) -> Client:
277-
if self.loop is MISSING:
277+
if self._loop is MISSING:
278278
try:
279-
self.loop = asyncio.get_running_loop()
279+
self._loop = asyncio.get_running_loop()
280280
except RuntimeError:
281281
# No event loop was found, this should not happen
282282
# because entering on this context manager means a
283283
# loop is already active, but we need to handle it
284284
# anyways just to prevent future errors.
285285

286286
# Maybe handle different system event loop policies?
287-
self.loop = asyncio.new_event_loop()
287+
self._loop = asyncio.new_event_loop()
288288

289289
self.http.loop = self.loop
290290
self._connection.loop = self.loop
@@ -822,10 +822,12 @@ async def runner():
822822
async with self:
823823
await self.start(token=token, reconnect=reconnect)
824824

825-
run = asyncio.run
826-
827-
if self.loop is not MISSING:
825+
try:
828826
run = self.loop.run_until_complete
827+
requires_cleanup = True
828+
except RuntimeError:
829+
run = asyncio.run
830+
requires_cleanup = False
829831

830832
try:
831833
run(runner())
@@ -834,8 +836,11 @@ async def runner():
834836
if not self.is_closed():
835837
self.loop.run_until_complete(self.close())
836838

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)
839844

840845
# properties
841846

0 commit comments

Comments
 (0)