Syncer

2.0.3 · active · verified Tue Apr 14

Syncer is a Python library designed to simplify the conversion of asynchronous functions to synchronous ones. It abstracts away the boilerplate of `asyncio.get_event_loop().run_until_complete()`, making it easier to call `async def` functions from synchronous contexts, particularly useful in testing or when integrating with synchronous codebases. The current version is 2.0.3, with releases occurring periodically to maintain compatibility and add features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the primary ways to use `syncer.sync`. It can convert an `async def` function into a synchronous callable, directly execute a coroutine object to retrieve its result, or be used as a decorator on `async def` test methods to run them in a synchronous test runner.

import asyncio
from syncer import sync

async def fetch_data():
    await asyncio.sleep(0.01) # Simulate an async I/O operation
    return "Async data fetched!"

# --- Usage 1: Run an async function synchronously (returns a callable) ---
synchronous_fetch = sync(fetch_data)
result_function_call = synchronous_fetch() # Call the returned synchronous function
print(f"Result from function call: {result_function_call}")

# --- Usage 2: Run a coroutine synchronously (returns the coroutine's result) ---
result_coroutine_run = sync(fetch_data())
print(f"Result from coroutine run: {result_coroutine_run}")

# --- Usage 3: As a decorator for synchronous test methods ---
import unittest

class MySyncTests(unittest.TestCase):
    @sync
    async def test_async_fetch(self):
        data = await fetch_data()
        self.assertEqual(data, "Async data fetched!")

# To run the tests (optional, for demonstration):
# if __name__ == '__main__':
#     unittest.main()

view raw JSON →