Skip to content

Commit

Permalink
Fix more event loop fetching
Browse files Browse the repository at this point in the history
Primarily due to version changes over time, this all used to work in
older versions, but Python 3.12 started issuing new warnings and errors
unless manual steps are used for event loop handling instead of automatic steps.

Fixes #2
  • Loading branch information
mattsta committed Aug 18, 2024
1 parent 2ae8bc8 commit 7af5787
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
14 changes: 12 additions & 2 deletions eventkit/util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import asyncio
import datetime as dt
import functools

from typing import AsyncIterator


Expand All @@ -16,9 +18,17 @@ def __repr__(self):
NO_VALUE = _NoValue()


@functools.cache
def get_event_loop():
"""Get asyncio event loop, running or not."""
return asyncio.get_event_loop_policy().get_event_loop()
"""Get asyncio event loop or create one if it doesn't exist."""
try:
# https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

return loop


async def timerange(start=0, end=None, step: float = 1) -> AsyncIterator[dt.datetime]:
Expand Down
3 changes: 1 addition & 2 deletions tests/create_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
array1 = list(range(10))
array2 = list(range(100, 110))

loop = asyncio.get_event_loop_policy().get_event_loop()


class CreateTest(unittest.TestCase):
def test_wait(self):
loop = asyncio.get_event_loop_policy().get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_later(0.001, fut.set_result, 42)
event = Event.wait(fut)
Expand Down
6 changes: 4 additions & 2 deletions tests/event_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import eventkit as ev
from eventkit import Event

loop = asyncio.get_event_loop_policy().get_event_loop()
run = loop.run_until_complete

def run(*args, **kwargs):
loop = asyncio.get_event_loop_policy().get_event_loop()
return loop.run_until_complete(*args, **kwargs)


class Object:
Expand Down
3 changes: 0 additions & 3 deletions tests/transform_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@

from eventkit import Event

loop = asyncio.get_event_loop_policy().get_event_loop()
loop.set_debug(True)

array = list(range(20))


Expand Down

0 comments on commit 7af5787

Please sign in to comment.