Contexter是ContextLib标准库模块的完全替换。它提供了更多的特性、更好的API和对Python2.5到3.x的完全支持(从单个源文件)。
contexter的Python项目详细描述
contexter是contextlib[1]标准库模块的完全替换。它提供了更多的特性、更好的API和对Python2.5到3.x的完全支持(从单个源文件)。
简而言之:contexter允许您以简单直观的方式嵌套和堆栈上下文管理器。
够了,让我们看一个例子:
''' Copy the content of one file to another and protect everything with a lock. '''withContexter(lock)asctx:in_file=ctx<<open('a.txt')out_file=ctx<<open('b.txt','w')out_file.write(in_file.read())
看看这个。很漂亮,不是吗?让我解释一下:调用Contexter()时,使用任意数量的上下文管理器作为参数,然后使用整洁的value = ctx << thing语法附加其他管理器。就这样。只有一级缩进,不管你需要多少经理。
仅供比较:
# Python 2.5 and 2.6withlock:withopen('a.txt')asin_file:withopen('b.txt','w')asout_file:out_file.write(in_file.read())# Starting with Python 2.7 and 3.2withlock,open('a.txt')asin_file,open('b.txt','w')asout_file:out_file.write(in_file.read())# Deprecated since Python 2.7 and 3.2withcontextlib.nested(lock,open('a.txt'),open('b.txt','w'))asvalues:in_file,out_file=valuesout_file.write(in_file.read())# Since Python 3.3 (not backported to 2.7)withcontextlib.ExitStack()asstack:stack.enter_context(lock)in_file=stack.enter_context(open('a.txt'))out_file=stack.enter_context(open('b.txt','w'))out_file.write(in_file.read())
替换contextlib.nested[2]
您可以使用Contexter(*managers)作为contextlib.nested(*managers)的替换,只需不使用confusing error prone quirks mentioned in the official documentation。
替换contextlib.closing[3]
算了吧。Contexter自动将可关闭的对象转换为上下文管理器。
替换contextlib.ExitStack[4]
contexter提供contextlib.ExitStack所做的一切(以及更多)。如果您想要一个也适用于python 2.x和3.2的drop-in替换,那么可以使用我们的后端口ExitStack,这是Contexter的一个子类,与contextlib变量兼容。
替换contextlib中的所有内容
如果你真的想坚持使用标准api,你可以。contexter在contextlib和backports中实现了所有的公共api新特性。
更多示例:
Contexter跟踪所有调用的上下文管理器的结果。您可以稍后访问结果,而不必在开始时全部解包。
withContexter(open('a.txt'),open('b.txt','w'))asctx:in_file,out_file=ctx.values()assertctx.value(0)isin_fileassertctx[0]isin_fileassertctx[0:2]==[in_file,out_file]assertlen(ctx)==2
如果您不喜欢<<语法,那么有一个方法也会这样做。
withContexter()asctx:in_file=ctx<<open('a.txt')out_file=ctx.append(open('b.txt','w'))
Contexter上下文是可嵌套的。每一层嵌套都维护自己的上下文管理器和结果值堆栈。这允许您非常精确地控制上下文的生存期。
withContexter()asctx:out_file=ctx<<open('b.txt','w')withctx:in_file=ctx<<open('a.txt')copy_data(in_file,out_file)assertin_file.closed==Trueassertout_file.closed==False
链接
[1] | http://docs.python.org/3/library/contextlib.html |
[2] | http://docs.python.org/2/library/contextlib.html#contextlib.nested |
[3] | http://docs.python.org/3/library/contextlib.html#contextlib.closing |
[4] | http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack |