如何在Python中的“if”语句下使用不同的“with”?

问题描述 投票:0回答:2

源代码如下:

with A:
    do_some()

我想根据

with
条件选择不同的
if
语句,如下面的代码。并且
do_some()
仍在
with
声明下。

if cond1:
    with A:
else:
    with B:
do_some() 

我该怎么做?

python
2个回答
0
投票

要在 Python 中实现此目的,您可以使用上下文管理器,根据您的

A
条件有条件地在
B
if
之间进行选择。

# Define a custom context manager
class ConditionalContextManager:
    def __enter__(self):
        # Enter method: returns the appropriate context manager based on condition
        if cond1:
            return A.__enter__()
        else:
            return B.__enter__()

    def __exit__(self, exc_type, exc_value, traceback):
        # Exit method: delegates to the appropriate context manager's exit method
        if cond1:
            return A.__exit__(exc_type, exc_value, traceback)
        else:
            return B.__exit__(exc_type, exc_value, traceback)

# Usage
with ConditionalContextManager():
    do_some()

0
投票

您可以将用作上下文管理器的对象保存为变量,然后再在

with
语句中使用它。

if cond1:
    context = A
else:
    context = B

with context:
    do_some()
© www.soinside.com 2019 - 2024. All rights reserved.