2016-12-20 39 views
0

我有這樣的:幾個「與....爲VAR1」符合條件

if condition1: 
    with func1() as var1: 
     with func2() as var2: 
     # a lot of stuff here 

    else: 
    with func2() as var2: 
     # the exact same stuff as above 

有沒有辦法做這樣的事情?

if condition1: 
    with func1() as var1: 
     ???? 

    # func2() is called anyway 
    with func2() as var2: 
    # a lot of stuff here 

與此相反:

def some_stuff(): 
    # a lof of stuff 

    if condition1: 
    with func1() as var1: 
     with func2() as var2: 
     some_stuff() 

    else: 
    with func2() as var2: 
     some_stuff() 

正如你所看到的,func2()無論如何調用,通過func1()只有當condtion是真實的。

+0

您能否解釋一下「我想要一個預處理器」的說法? –

+0

@BhargavRao,更新。 – Kurama

+0

不會把'func2()作爲var2:'if else'之外的塊按預期工作嗎? –

回答

2

當條件爲False時,您可以使用虛擬上下文管理器創建條件上下文管理器。

,您可以用逗號

import contextlib 
@contextlib.contextmanager 
def dummy_context_manager(): 
    yield None 

with func1() if condition1 else dummy_context_manager() as var1, func2() as var2: 
    # do your stuff here 
    some_stuff() 
3

最好的解決辦法仍然是分離出「很多東西」到一個單獨的功能合併雙方的VAR1和VAR2上下文管理。但是,你可以使用contextlib.ExitStack(需要v3.3 +)來處理這樣的事情。

from contextlib import ExitStack 

with ExitStack() as stack: 
    if condition: 
     var1 = stack.enter_context(func1()) 
    var2 = stack.enter_context(func2()) 

    ... # stuff 

# all context managers handled by stack are exited at the end of the block