Python Async to Sync | Cododel
CODODELDEV
EN / RU
Back to Deck
[snippet]

Python Async to Sync

SOURCE Python
VERSION 1.0
AUTHOR Cododel

A simple utility for synchronously executing async functions while preserving type information. The IDE correctly determines the return type thanks to TypeVar usage.

The Problem

With regular asyncio.run(), the IDE loses type information:

async def fetch_book(id: int) -> BookModel:
...
# IDE doesn't know this is BookModel
book = asyncio.run(fetch_book(123))

The Solution

Using sync_await with proper typing via TypeVar:

book = sync_await(fetch_book(4325)) # ✅ IDE correctly infers type as BookModel
print(book.title) # Autocomplete works!

Usage

example.py

from sync_await import sync_await
class BookModel(BaseModel):
id: int
title: str
content: str
async def fetch_book(id: int) -> BookModel:
...
if __name__ == "__main__":
book = sync_await(fetch_book(4325)) # The IDE will correctly determine the type of the book variable
print(book.title)

Source Code

sync_await.py

from typing import Coroutine, TypeVar, Any
import asyncio
from pydantic import BaseModel
T = TypeVar('T')
def sync_await(coroutine: Coroutine[Any, Any, T]) -> T:
return asyncio.run(coroutine)

How It Works

  1. TypeVar('T') - creates a generic type variable
  2. Coroutine[Any, Any, T] - a coroutine returning type T
  3. -> T - function returns the same type T
  4. IDE sees the connection between coroutine type and result
[ ▲ 0 ]