Skip to the content

Context managers

Python · Unit 21: Advanced Python

with open(...) closes the file on its own. Any object can be used with with if it has two methods: __enter__ runs when you enter the block and __exit__ when you leave it.

__exit__ receives details of the error if there was one; with *args it takes them all without using them.

class Frame:
    def __enter__(self):
        print("== start")
    def __exit__(self, *args):
        print("== end")

with Frame():
    print("Ana: 9")

Prints

== start
Ana: 9
== end

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Fill in the blank so the bell rings on the way in and on the way out of the block.

  4. 4. Find the bug

    It should print open, through and close. Which line has the error?

  5. 5. Predict the output

    What does this code print?

  6. 6. Complete the code

    Fill in the blank so the turn announces when it starts and when it ends.

  7. 7. Put the lines in order

    Put the lines in order so the expense comes out between brackets under its title.

  8. 8. Multiple choice

    What does with give you over writing the closing line yourself at the end of the block?

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →