如何处理with语句中的动态项目数?

时间:2017-10-19 23:56:34

标签: python with-statement

是否有一种很好的方法可以复制以下代码以使用单个with语句:

thing1 = Thing()
if two_things: 
    thing2 = Thing()

do_stuff(thing1)

if two_things:
    do_stuff(thing2)

thing1.close()
if two_things: 
    thing2.close()

我可以使用2个单独的子句,但如果在这两个案例之间共享很多代码,那就非常糟糕了。

if two_things:
    with Thing() as thing1, Thing() as thing2:
        do_stuff(thing1)
        do_stuff(thing2)

else: 
    with Thing() as thing:
        do_stuff(thing1)

1 个答案:

答案 0 :(得分:2)

"Supporting a variable number of context managers"

  

ExitStack的主要用例是类文档中给出的用例:在单个with语句中支持可变数量的上下文管理器和其他清理操作。可变性可能来自需要由用户输入驱动的上下文管理器的数量(例如打开用户指定的文件集合),或者来自某些上下文管理器是可选的:

with ExitStack() as stack:
    for resource in resources:
        stack.enter_context(resource)
    if need_special_resource():
        special = acquire_special_resource()
        stack.callback(release_special_resource, special)
    # Perform operations that use the acquired resources
相关问题