Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions newsfragments/51.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
``current_async_library`` now reports ``asyncio`` when an event loop is
running but there is no current Task, such as in ``call_soon`` callbacks
and Twisted's asyncioreactor. Detection uses ``asyncio.get_running_loop()``
only; ``current_task()`` is a slower subset of the same check.
9 changes: 3 additions & 6 deletions sniffio/_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,11 @@ async def generic_sleep(seconds):
if "asyncio" in sys.modules:
import 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"
asyncio.get_running_loop()
except RuntimeError:
pass
else:
return "asyncio"

# Sniff for curio (for now)
if 'curio' in sys.modules:
Expand Down
21 changes: 21 additions & 0 deletions sniffio/_tests/test_sniffio.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,27 @@ async def this_is_asyncio():
current_async_library()


def test_asyncio_running_loop_without_task():
import asyncio

result = []

def sync_cb():
try:
result.append(current_async_library())
finally:
loop.stop()

loop = asyncio.new_event_loop()
try:
loop.call_soon(sync_cb)
loop.run_forever()
finally:
loop.close()

assert result == ["asyncio"]


@pytest.mark.skipif(
sys.version_info >= (3, 12),
reason=
Expand Down