2017-10-19 37 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 
関連する問題