Skip to content

Instantly share code, notes, and snippets.

@websmithcode
Created August 8, 2024 23:40
Show Gist options
  • Save websmithcode/27c39abdad2d7af44572a7c48e9df1d8 to your computer and use it in GitHub Desktop.
Save websmithcode/27c39abdad2d7af44572a7c48e9df1d8 to your computer and use it in GitHub Desktop.
Async to Sync python with correct type definition
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_data(4325)) # The IDE will correctly determine the type of the book variable
print(book.title)
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)
@websmithcode
Copy link
Author

Subscribe to my telegram channel, don’t miss new interesting solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment