diff --git a/sniffio/_impl.py b/sniffio/_impl.py index c1a7bbf..3736c09 100644 --- a/sniffio/_impl.py +++ b/sniffio/_impl.py @@ -75,15 +75,24 @@ async def generic_sleep(seconds): if "asyncio" in sys.modules: import asyncio try: - current_task = asyncio.current_task # type: ignore[attr-defined] + asyncio.get_running_loop() + return "asyncio" + except AttributeError: - current_task = asyncio.Task.current_task # type: ignore[attr-defined] - try: - if current_task() is not None: - return "asyncio" + try: + current_task = asyncio.current_task # type: ignore[attr-defined] + except AttributeError: + current_task = asyncio.Task.current_task # type: ignore[attr-defined] + try: + if current_task() is not None: + return "asyncio" + except RuntimeError: + pass + except RuntimeError: pass + # Sniff for curio (for now) if 'curio' in sys.modules: from curio.meta import curio_running diff --git a/sniffio/_tests/test_sniffio.py b/sniffio/_tests/test_sniffio.py index 984c8c0..1b3babe 100644 --- a/sniffio/_tests/test_sniffio.py +++ b/sniffio/_tests/test_sniffio.py @@ -58,6 +58,30 @@ async def this_is_asyncio(): current_async_library() +def test_in_call_soon_threadsafe(): + import asyncio + + asynclib = None + + def sync_in_loop(completed): + nonlocal asynclib + try: + asynclib = current_async_library() + finally: + completed.set() + + async def async_in_loop(): + completed = asyncio.Event() + loop.call_soon_threadsafe(sync_in_loop, completed) + await completed.wait() + + loop = asyncio.new_event_loop() + loop.run_until_complete(async_in_loop()) + loop.close() + + assert asynclib == 'asyncio' + + # https://github.com/dabeaz/curio/pull/354 @pytest.mark.skipif( os.name == "nt" and sys.version_info >= (3, 9),