您的位置:首页 > 编程语言 > Python开发

python的with用法

2014-11-02 10:13 357 查看
代替try...finally做一些清理工作什么的

语法

with context_expression [as target(s)]:
with-body

用于文件的情况
with open(r'somefileName') as somefile:
for line in somefile:
print line
# ...more code

等价于
somefile = open(r'somefileName')
try:
for line in somefile:
print line
# ...more code
finally:
somefile.close()

如果自己写的一个玩意,比如数据库连接啥的发生异常要关闭,只要重写方法里面的__enter__() 方法和 __exit__() 方法
class _ConnectionCtx(object):
def __enter__(self):
global _db_ctx
self.should_cleanup = False
if not _db_ctx.is_init():
_db_ctx.init()
self.should_cleanup = True
return self

def __exit__(self, exctype, excvalue, traceback):
global _db_ctx
if self.should_cleanup:
_db_ctx.cleanup()

def connection():
return _ConnectionCtx()

使用
with connection():
do_some_db_operation()

更好的做法,用一个迭代器包含掉上面的with
class _ConnectionCtx(object):
def __enter__(self):
global _db_ctx
self.should_cleanup = False
if not _db_ctx.is_init():
_db_ctx.init()
self.should_cleanup = True
return self

def __exit__(self, exctype, excvalue, traceback):
global _db_ctx
if self.should_cleanup:
_db_ctx.cleanup()

def with_connection(func):
@functools.wraps(func)
def _wrapper(*args, **kw):
with _ConnectionCtx():
return func(*args, **kw)
return _wrapper使用
@with_connection
def do_some_db_operation():
pass
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: