Easy tool enabling async & sync calls on the same method with Python.
Designed when migrating code, to allow for gradual transition to async or interop with sync codebase aswell.
- Async and Sync Compatibility: Easily create functions that work in both synchronous and asynchronous contexts.
- Flexible Initialization: Use
AsyncObj
for classes requiring asynchronous initialization. - Decorator for Async Methods: Simplify async method usage with the
sync_compat
decorator.
Install via pip:
pip install syncra
Create a function that can be called synchronously or asynchronously:
from syncra import sync_async_factory
import asyncio
def sync_func(x):
return x * 2
async def async_func(x):
await asyncio.sleep(0.1)
return x * 2
syncra = sync_async_factory(sync_func, async_func)
# Usage:
result = syncra(5) # Synchronous
async def main(): # Asynchronous
result = await syncra(5)
Make an async function compatible with sync calls
from syncra import sync_compat
import asyncio
@sync_compat
async def async_function(x):
await asyncio.sleep(0.1)
return x * 2
# Usage:
result = async_function(5) # Synchronous
async def main(): # Asynchronous
result = await async_function(5)
Create a class that can be initialized asynchronously:
from syncra import AsyncObj
class MyAsyncClass(AsyncObj):
async def __ainit__(self, x):
self.x = x
# Usage:
async def main():
obj = await MyAsyncClass(10)
print(obj.x)
This project is licensed under the MIT License.