Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: async_run to allow nested event loops. #1170

Merged
merged 2 commits into from Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 17 additions & 1 deletion snakemake/common/__init__.py
Expand Up @@ -37,7 +37,23 @@ def async_run(coroutine):


else:
async_run = asyncio.run

def async_run(coroutine):
"""Attaches to running event loop or creates a new one to execute a
coroutine.

.. seealso::

https://github.com/snakemake/snakemake/issues/1105
https://stackoverflow.com/a/65696398

"""
try:
_ = asyncio.get_running_loop()
except RuntimeError:
asyncio.run(coroutine)
else:
asyncio.create_task(coroutine)


# A string that prints as TBD
Expand Down
25 changes: 25 additions & 0 deletions tests/testapi.py
Expand Up @@ -2,6 +2,8 @@
Tests for Snakemake’s API
"""
from snakemake import snakemake
import asyncio
import sys
import tempfile
import os.path
from textwrap import dedent
Expand Down Expand Up @@ -32,3 +34,26 @@ def test_run_script_directive():
file=f,
)
snakemake(path, workdir=tmpdir)


def test_run_script_directive_async():
"""Tests :func`snakemake.common.async_run`. The test ensure the ability to
execute Snakemake API even if an asyncio event loop is already running.

"""
import tracemalloc
from snakemake.common import async_run

tracemalloc.start()

async def dummy_task():
await asyncio.sleep(0.00001)

async def main():
async_run(dummy_task())
test_run_script_directive()

if sys.version_info < (3, 7):
async_run(main())
else:
asyncio.run(main())