Skip to content

Instantly share code, notes, and snippets.

@whiledoing
Last active June 29, 2017 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whiledoing/988bc3670aa838465ddf953d486762f9 to your computer and use it in GitHub Desktop.
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
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
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