Break or exit out of “with” statement?

后端 未结 12 2222
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 11:04

I\'d just like to exit out of a with statement under certain conditions:

with open(path) as f:
    print \'before condition\'
    if 

        
12条回答
  •  萌比男神i
    2020-12-02 11:38

    There exists a function __exit__() for this purpose. Syntax is as follows:

    with VAR = EXPR:
      try:
        BLOCK
      finally:
        VAR.__exit__()
    

提交回复
热议问题