Skip to content

Instantly share code, notes, and snippets.

@92hackers
Created September 21, 2017 12:06
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 92hackers/07766cf03e98d1f18904cfb51a724315 to your computer and use it in GitHub Desktop.
Save 92hackers/07766cf03e98d1f18904cfb51a724315 to your computer and use it in GitHub Desktop.
Three kinds of method to establish a with context
with open('file') as f:
data = f.read()
print(data)
# with expression construct a context
# class method,最关键的是,context 本质上就是 __enter__, __exit__ 这两个方法,with 会自动的运行这两个方法。
class CustomOpen(object):
def __init__(self, filename):
self.file = open('filename')
def __enter__(self):
return self.file
def __exit__(self, ctx_type, ctx_value, ctx_traceback):
self.file.close()
with CustomOpen('file') as f:
data = f.read()
print(data)
# contextmanager, 相当于封装了 __enter__, __exit__ 这些方法,做成一个 decorator,
# 这种方法更加的简洁,用到了 generator.类似一个异步运行,yield 下面的相当于是回调, 当 yield 部分执行完的时候,就执行回调部分。
from contextlib import contextmanager
@contectmanager
def custom_open(filename):
fd = open(filename)
try:
yield fd
finally:
fd.close()
@92hackers
Copy link
Author

感觉对于 generator 有了一点理解。 确实运用于 node.js 的异步模型非常棒。

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