0

Is there any pattern that allows you to exit from a Context Manager and return the control flow to the code following the with (...):?

For example (doesn't actually work):

with open('/etc/passwd', 'r') as f:
    f.seek(0, 2)
    if f.tell() < 10:
        print "The file is too small!"
        break

    # Process the file.

Is there anything I can replace break with to do the same thing?

Will
  • 24,082
  • 14
  • 97
  • 108

1 Answers1

1

it doesnt look like you can exit from with but you can wrap it in a loop so you can exit - eg like so

for _ in [0]:
    with open('/etc/passwd', 'r') as f:
        f.seek(0, 2)
        if f.tell() < 10:
            print "The file is too small!"
            break

but propably using exceptions (like mentioned in the comments) or wrapping in a function and returning (I would prefer returning) is more natural.

janbrohl
  • 2,626
  • 1
  • 17
  • 15