10. contextlib模块

suppress

忽略异常并正常执行

from contextlib import suppress

with suppress(Exception):
  # your code

contextmanager

上下文管理器

from contextlib import contextmanager

@contextmanager
def make_open_context(filename, mode):
    fp = open(filename, mode)
    try:
        yield fp
    finally:
        fp.close()

with make_open_context('/tmp/a', 'a') as f:
    f.write('hello world')

yield关键词把上下文分割成两部分:yield之前就是__init__中的代码块; yield之后其实就是__exit__中的代码块;yield生成的值会绑定到with语句as子句中的变量(如果没有生成,也就没有as字句