Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python - Break or exit out of "with" statement?

I'd just like to exit out of a with statement under certain conditions:

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

Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition: if not <condition>: print 'after condition' -- any way that is like above?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

with giving you trouble? Throw more with-able objects at the problem!

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

Just wrap the expression you're going to with with fragile, and raise fragile.Break to break out at any point!

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

Benefits of this setup

  • Uses with and just the with; doesn't wrap your function in a semantically misleading one-run 'loop' or a narrowly specialized function, and doesn't force you to do any extra error handling after the with.
  • Keeps your local variables available, instead of having to pass them to a wrapping function.
  • Nestable!

    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!"
    

    This way, you don't have to create a new function to wrap the outer with if you want both to break.

  • Doesn't require restructuring at all: just wrap what you already have with fragile and you're good to go!

Downsides of this setup

  • Doesn't actually use a 'break' statement. Can't win em all ;)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...