Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Created December 12, 2018 20:00
Show Gist options
  • Save a-recknagel/e474a179808b173b9facfde2b0b523b0 to your computer and use it in GitHub Desktop.
Save a-recknagel/e474a179808b173b9facfde2b0b523b0 to your computer and use it in GitHub Desktop.
Context manager with __exit__ having access __enter__'s returned value
from functools import lru_cache
class File:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
@lru_cache(1)
def __enter__(self):
return open(self.filename, self.mode)
def __exit__(self, *args):
self.__enter__().close()
@a-recknagel
Copy link
Author

This is actually really bad code and this pattern should be used instead.

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