2017-10-19 58 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