Break or exit out of “with” statement?

后端 未结 12 2232
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 11:31

    Since break can only occur inside a loop your options are somewhat limited inside the with to:

    • return (put "with" + associated statements inside function)
    • exit (bail from program - probably not ideal)
    • exception (generate exception inside "with", catch below)

    Having a function and using return is probably the cleanest and easiest solution here if you can isolate the with and the associated statements (and nothing else) inside a function.

    Otherwise generate an exception inside the with when needed, catch immediately below/outside the with to continue the rest of the code.

    Update: As OP suggests in the comments below (perhaps tonuge in cheek?) one could also wrap the with statement inside a loop to get the break to work - though that would be semantically misleading. So while a working solution, probably not something that would be recommend).

提交回复
热议问题