Created
March 7, 2023 15:40
-
-
Save Akasurde/33261ba8ff5ff34ed753675948d55c53 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import asyncio | |
from typing import Optional, Dict, Any | |
class AsyncFile: | |
def __init__(self, file_path: str, mode: str = "r", **kwargs: Optional[Dict[str, Any]]): | |
self.file_path = file_path | |
self.mode = mode | |
self.kwargs = kwargs | |
self.file = None | |
async def __aenter__(self): | |
self.file = await asyncio.to_thread( | |
open, self.file_path, mode=self.mode, **self.kwargs | |
) | |
return self.file | |
async def __aexit__(self, exc_type, exc_val, exc_tb): | |
self.file.close() | |
async def __enter__(self): | |
return await self.__aenter__() | |
async def __exit__(self, exc_type, exc_val, exc_tb): | |
return await self.__aexit__(exc_type, exc_val, exc_tb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment