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
语法
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
相关文章推荐
- python with语句的用法
- python学习:异常处理、with用法以及utf8中文显示
- python中with和contextlib的用法
- Python中with...as的用法
- 详解Python中with语句的用法
- python with...as...用法
- python with用法
- 学习Python:with...as的用法
- python -with用法
- Python中的with...as用法介绍
- python中关于with及contextlib的用法
- Python with语句用法
- 【ZZ】python with...as...用法
- Python的with...as的用法
- Python with的用法
- python中关于with及contextlib的用法
- python中with的用法
- python 中关于with...as的用法
- python with...as...用法
- python with...as...用法