if tb is None:
# No exception, so commit
self.commit()
else:
# Exception occurred, so rollback.
self.rollback()
# return False
8.2 The contextlib module
The new contextlib module provides some functions and a decorator that
are useful
for writing objects for use with the 'with' statement.
2.5新加的contextlib模块提供了一些用于编写供'with'语句使用的对象的方法和decorator。
The decorator is called contextfactory, and lets you write a single generator
function instead of defining a new class. The generator should yield
exactly one value.
The code up to the yield will be executed as the __enter__() method,
and the value yielded will be the method's return value that will get
bound to the
variable in the 'with' statement's as clause, if any. The code after
the yield will be
executed in the __exit__() method. Any exception raised in the block
will be raised
by the yield statement.
这个decorotor被称为contextfactory。有了它,你可以只写一个generator方法
而不用去定义一个新的类了。这个generator只能yield一个值。yield之前的代码表示__enter__()方法,
yield出来的值会绑定到 with 语句的 as 子句的变量,如果有的话。yield后面的代码是__exit__()要执行的。
此外,yield还会把block里面的异常再抛出来。
Our database example from the previous section could be written using
this decorator as:
我们前面讲的数据库的例子可以这样改写:
from contextlib import contextfactory
@contextfactory
def db_transaction (connection):
cursor = connection.cursor()
try:
yield cursor
except:
connection.rollback()
raise
else:
connection.commit()
db = DatabaseConnection()
with db_transaction(db) as cursor:
| 论坛热门帖子: | [lch203] 写得蛮好的linux学习笔记(10-21) [黑马制造] 学习java的30个目标(10-19) [笑傲股林] 做测试半年了,有点迷茫,应该再学些什么提高自己的测试水平和测试能力呢?(10-19) [udp8589] 大家用google的来吱一声? 用百度的~~也来报道下?(10-18) [沂偌掳兆] 本人总结的一些认为C++比较经典的书籍,希望对大家有用(10-18) |
| TAG标签: | with 一个 对象 语句 这个 方法 异常 如果 可以 返回 |
注册
个人空间
