中断或退出“with”语句?

2024-03-29 15:01:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想在特定条件下退出with语句:

with open(path) as f:
    print 'before condition'
    if <condition>: break #syntax error!
    print 'after condition'

当然,上面的不起作用。有办法吗?(我知道我可以反转条件:if not <condition>: print 'after condition'——任何类似的方式?)


Tags: pathifaswitherror语句opencondition
3条回答

最好的方法是将其封装在函数中并使用return

def do_it():
    with open(path) as f:
        print 'before condition'
        if <condition>:
            return
        print 'after condition'

给你添麻烦?在这个问题上抛出更多的with对象!

class fragile(object):
    class Break(Exception):
      """Break out of the with statement"""

    def __init__(self, value):
        self.value = value

    def __enter__(self):
        return self.value.__enter__()

    def __exit__(self, etype, value, traceback):
        error = self.value.__exit__(etype, value, traceback)
        if etype == self.Break:
            return True
        return error

只要用fragile来包装你要with的表达式,然后raise fragile.Break就可以在任何时候爆发!

with fragile(open(path)) as f:
    print 'before condition'
    if condition:
        raise fragile.Break
    print 'after condition'

此设置的好处

  • 使用with,并且仅使用with;不会将函数包装在语义上具有误导性的一次运行“循环”或狭义专用的函数中,也不会强制您在with之后执行任何额外的错误处理。
  • 保持局部变量可用,而不必将它们传递给包装函数。
  • 舒适!

    with fragile(open(path1)) as f:
        with fragile(open(path2)) as g:
            print f.read()
            print g.read()
            raise fragile.Break
            print "This wont happen"
        print "This will though!"
    

    这样,如果您希望两者都断开,就不必创建新函数来包装外部with

  • 完全不需要重组:只要用fragile包装好你已经拥有的东西,你就可以走了!

这种设置的缺点

  • 实际上不使用“break”语句。不可能全部赢;)

我认为你应该调整一下逻辑:

with open(path) as f:
    print 'before condition checked'
    if not <condition>:
        print 'after condition checked'

相关问题 更多 >