Skip to content

Commit 30c0c1d

Browse files
committed
feat : Added new decorator - async_safe.
1 parent ff0f7a6 commit 30c0c1d

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

decorators/async_safe.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import asyncio
2+
import functools
3+
4+
5+
def async_safe(func):
6+
"""Wrap a sync function to make it awaitable in async contexts."""
7+
@functools.wraps(func)
8+
async def wrapper(*args, **kwargs):
9+
loop = asyncio.get_running_loop()
10+
return await loop.run_in_executor(None, lambda: func(*args, **kwargs))
11+
return wrapper

tests/test_async_safe.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import asyncio
2+
3+
import pytest
4+
from decorators.async_safe import async_safe
5+
6+
7+
@async_safe
8+
def sync_add(x, y):
9+
return x + y
10+
11+
12+
@pytest.mark.asyncio
13+
async def test_async_safe():
14+
result = await sync_add(2, 3)
15+
assert result == 5

0 commit comments

Comments
 (0)