中止一个带有变量的块而不是提高?

Abort a block with a variable and not raising?

我希望 ifwith 或替代语句不会在有副作用的情况下进入块,例如类似这样:

with sometimes_run_block() as value:
    print('this should only sometimes run', value)

with 语句上下文看起来像这样:

@contextmanager
def sometimes_run_block():
    if random.random() > 0.5:
        yield 'hello!'
    else:
        yield 

目前,我在 @contextmanager 装饰函数中没有产生任何结果,并检查该值是否不是 None。对我来说,进行提取检查似乎是多余的,导致它是三行和两级缩进:

with sometimes_run_block() as value:
    if value:
        print('this should only sometimes run', value)

另一种选择是不使用 with:

value = sometimes_run_block()
if value:
    print('this should only sometimes run', value)

当前有效的两行解决方案是使用 for 语句,但它具有误导性。

for value in sometimes_run_block():
    print('this should only sometimes run', value)

是否可以跳过上下文块的处理(就好像它是一个 if 语句)但在引入上下文变量时不引发异常?

简单的方法是最好的方法:

value = sometimes_run_block()
if value:
    print('this should only sometimes run', value)

这就是Python,毕竟——我们不倾向于追逐周期,我们不重视简洁胜过清晰。如果你想做一些古怪的事情,这取决于你,但以后维护你的代码的人希望在它把他们逼疯之前弄清楚如何撤消它。