Created
August 8, 2024 23:40
-
-
Save websmithcode/27c39abdad2d7af44572a7c48e9df1d8 to your computer and use it in GitHub Desktop.
Async to Sync python with correct type definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Subscribe to my telegram channel, don’t miss new interesting solutions