-
-
Save a-recknagel/e474a179808b173b9facfde2b0b523b0 to your computer and use it in GitHub Desktop.
Context manager with __exit__ having access __enter__'s returned value
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
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is actually really bad code and this pattern should be used instead.