2017-10-19 76 views
1

是否有复制下面的代码使用单个with声明一个不错的方式:如何处理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) 

回答

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