Contexter是contextlib标准库模块的全替代品。它包含更多功能,更好的API,并从单个源文件支持Python 2.5到3.x的全版本。
项目描述
Contexter是contextlib [1]标准库模块的全替代品。它包含更多功能,更好的API,并从单个源文件支持Python 2.5到3.x的全版本。
简而言之:Contexter允许您以简单直观的方式嵌套和堆叠上下文管理器。
不多说了,让我们看看一个例子
''' Copy the content of one file to another
and protect everything with a lock. '''
with Contexter(lock) as ctx:
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.6
with lock:
with open('a.txt') as in_file:
with open('b.txt', 'w') as out_file:
out_file.write(in_file.read())
# Starting with Python 2.7 and 3.2
with lock, open('a.txt') as in_file, open('b.txt', 'w') as out_file:
out_file.write(in_file.read())
# Deprecated since Python 2.7 and 3.2
with contextlib.nested(lock, open('a.txt'), open('b.txt', 'w')) as values:
in_file, out_file = values
out_file.write(in_file.read())
# Since Python 3.3 (not backported to 2.7)
with contextlib.ExitStack() as stack:
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)的替代品,只是没有官方文档中提到的令人困惑且易出错的特性。
替代contextlib.closing [3]
就忘掉它吧。Contexter会自动将可关闭对象转换为上下文管理器。
替换 contextlib.ExitStack [4]
Contexter 提供了 contextlib.ExitStack 所有的功能(以及更多)。如果您需要一个同时适用于 Python 2.x 和 3.2 的即插即用替换方案,可以使用我们反向移植的 ExitStack,它是 Contexter 的一个子类,与 contextlib 变体的 API 兼容。
替换 contextlib 中其他所有内容
如果您真的想坚持标准 API,您也可以这样做。Contexter 实现了 contextlib 的所有公共 API,并在新功能引入时立即反向移植。
更多示例
Contexter 会跟踪所有调用的上下文管理器的结果。您可以稍后访问这些结果,而无需一开始就全部展开。
with Contexter(open('a.txt'), open('b.txt', 'w')) as ctx:
in_file, out_file = ctx.values()
assert ctx.value(0) is in_file
assert ctx[0] is in_file
assert ctx[0:2] == [in_file, out_file]
assert len(ctx) == 2
如果您不喜欢 <<<< 语法,有一个方法可以做到同样的事情。
with Contexter() as ctx:
in_file = ctx << open('a.txt')
out_file = ctx.append(open('b.txt', 'w'))
Contexter 上下文是可嵌套的。每个嵌套级别的上下文都维护自己的上下文管理器和结果值栈。这允许您非常精确地控制上下文的生命周期。
with Contexter() as ctx:
out_file = ctx << open('b.txt', 'w')
with ctx:
in_file = ctx << open('a.txt')
copy_data(in_file, out_file)
assert in_file.closed == True
assert out_file.closed == False
链接
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪一个,请了解有关 安装包 的更多信息。