Last active
June 29, 2017 19:46
-
-
Save whiledoing/988bc3670aa838465ddf953d486762f9 to your computer and use it in GitHub Desktop.
[python-context-manager] using class and context manager method to implement python context manager #python
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
class Context(object): | |
def __init__(self, name): | |
self.file = open(name) | |
def __enter__(self): | |
return self.file | |
def __exit__(self, ctx_type, ctx_value, ctx_traceback): | |
self.file.close() | |
with Context('xxx') as f: | |
pass |
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
import contextlib | |
@contextlib.contextmanager | |
def custom_open(filename): | |
try: | |
f = open(filename) | |
yield f | |
finally: | |
f.close() | |
with custom_open('file') as f: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment