Python中的带条件语句 [英] Conditional with statement in Python

查看:79
本文介绍了Python中的带条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以用with语句开始一段代码,但是有条件地?

Is there a way to begin a block of code with a with statement, but conditionally?

类似的东西:

if needs_with():
    with get_stuff() as gs:

# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()

为了澄清,一种情况下会有一个块包裹在with语句中,而另一种可能性是相同的块,但没有包裹(即好像没有缩进)

To clarify, one scenario would have a block encased in the with statement, while another possibility would be the same block, but not encased (i.e., as if it wasn't indented)

初始实验当然会产生缩进错误。.

Initial experiments of course give indentation errors..

推荐答案

如果要避免重复代码,并使用3.7之前的Python版本(当<$ c甚至引入了$ c> contextlib.nullcontext )或3.3(引入了 contextlib.ExitStack )时,您可以执行以下操作:

If you want to avoid duplicating code and are using a version of Python prior to 3.7 (when contextlib.nullcontext was introduced) or even 3.3 (when contextlib.ExitStack was introduced), you could do something like:

class dummy_context_mgr():
    def __enter__(self):
        return None
    def __exit__(self, exc_type, exc_value, traceback):
        return False

或:

import contextlib

@contextlib.contextmanager
def dummy_context_mgr():
    yield None

,然后将其用作:

with get_stuff() if needs_with() else dummy_context_mgr() as gs:
   # do stuff involving gs or not

您也可以使 get_stuff()根据 needs_with()<返回不同的东西

(请参阅迈克的答案 Daniel的答案,了解您在以后的版本中可以做什么。)

(See Mike's answer or Daniel's answer for what you can do in later versions.)

这篇关于Python中的带条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆