# python contextManager详解

contextlib.contextmanager(func)

This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods.

A simple example (this is not recommended as a real way of generating HTML!):

from contextlib import contextmanager

@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name

>>> with tag("h1"):
...    print "foo"
...
<h1>
foo
</h1>


The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any.

At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try...except...finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement.

#### @contextmanager:Python实现with结构的好方法

2016-10-25 20:13:46

#### Python学习笔记（五）-- 上下文管理器（Context Manager）

2016-10-11 18:20:24

#### Python with语句及context manager

2016-06-26 17:16:45

#### 十六、Python 上下文管理 Context Manager

2015-05-05 15:22:07

#### Python @contextmanager修饰器

2017-11-30 10:37:53

#### Python标准模块--ContextManager(上下文管理器)

2017-06-29 15:36:31

#### python-动态特性学习

2015-08-24 16:21:10

#### Python动态特性

2015-11-22 02:18:19

#### 详解Python的Django框架中Manager方法的使用

2017-05-23 13:53:34

#### python知识点：上下文管理器[__enter__ 和 __exit__ ]

2017-03-21 21:55:03