Skip to content

Instantly share code, notes, and snippets.

@Akasurde
Created March 7, 2023 15:40
Show Gist options
  • Save Akasurde/33261ba8ff5ff34ed753675948d55c53 to your computer and use it in GitHub Desktop.
Save Akasurde/33261ba8ff5ff34ed753675948d55c53 to your computer and use it in GitHub Desktop.
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