【问题标题】:Combining if and with in python?在python中结合if和with?
【发布时间】:2020-03-29 14:27:06
【问题描述】:

我想知道是否可以有条件地使用 with 语句,比如

if condition:
    with mock.patch(....)
#code that is or is not patched

理论上是否可以在不丢失 with 语句的情况下实现这一点?

【问题讨论】:

  • 目前尚不清楚您要在这里实现什么。请创建一个更全面的示例来显示所需的行为。
  • 丢失with 语句是什么意思?
  • 这能回答你的问题吗? Conditional with statement in Python
  • 我假设如果满足条件,您希望将 with 应用于注释下方的代码。可能有更好的方法 - 请分享一段较长的代码,以便我们查看上下文。

标签: python


【解决方案1】:

您可以创建一个包装上下文管理器,根据给定条件调用包装上下文管理器的__enter____exit__ 方法:

class conditional_context_manager:
    def __init__(self, condition, context_manager):
        self.condition = condition
        self.context_manager = context_manager

    def __enter__(self):
        return self.context_manager.__enter__() if self.condition else self

    def __exit__(self, *args, **kwargs):
        if self.condition:
            return self.context_manager.__exit__(*args, **kwargs)

这样:

with conditional_context_manager(False, mock.patch('builtins.print')):
    print('hi')

输出:

hi

同时:

with conditional_context_manager(True, mock.patch('builtins.print')):
    print('hi')

什么都不输出。

或者,如果条件不满足,您可以使用mock.MaigicMock 对象作为上下文管理器:

with mock.patch('builtins.print') if condition else mock.MagicMock():
    #code that is or is not patched

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2016-06-18
    • 2010-11-19
    • 2020-02-22
    • 2017-06-12
    • 2011-04-10
    • 2022-01-21
    • 2018-08-12
    • 1970-01-01
    相关资源
    最近更新 更多