有没有办法用with语句开始一段代码,但是有条件地?
就像是:
if needs_with():
with get_stuff() as gs:
# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()
Run Code Online (Sandbox Code Playgroud)
为了澄清,一种情况会在with语句中包含一个块,而另一种情况可能是同一个块,但不包含(即,好像它没有缩进)
最初的实验当然会给出压痕错误..
python conditional indentation with-statement conditional-statements