Created
September 21, 2017 12:06
-
-
Save 92hackers/07766cf03e98d1f18904cfb51a724315 to your computer and use it in GitHub Desktop.
Three kinds of method to establish a with context
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
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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
感觉对于 generator 有了一点理解。 确实运用于 node.js 的异步模型非常棒。