Python 3D Academyবাংলা

with: always clean up

🌍 In real life. You borrow a book from the library, read it, and give it back. But what if you spill tea on it halfway through? You still have to return the book. Good habits make sure the clean-up step always happens, whatever goes wrong in the middle.

Programs borrow things too: an open file, a network connection, a lock. A with block makes the clean-up automatic:

  • on the way in, a setup step runs (open the file, borrow the book)
  • then your block runs
  • on the way out, a clean-up step runs (close the file, return the book), even if the block raised an error

The idea in one sentence: with something as name: sets something up, runs the block, and always cleans up at the end, even if the block raises an error.

Its words:

  • context manager: an object that knows how to set up and clean up, like an open file
  • clean-up: the step that must always happen, like closing a file
  • try/finally: what with does for you behind the scenes

You met with in Chapter 20 for files. Here is why it's better than calling close() yourself, step by step:

  1. with plain open and close, an error before close() means your code never closes the file, and what you wrote may not be saved yet
  2. try/finally fixes that: the finally part always runs
  3. with open(...) as f: does the same try/finally work for you, in one short line
f = open("notes.txt")
try:
    print(f.readline().strip())
finally:
    f.close()              # always runs
print("closed?", f.closed)

with open("notes.txt") as f:
    print(f.readline().strip())
print("closed?", f.closed)  # with closed it for us
def borrow(spill):
    print("book borrowed")
    try:
        print("reading")
        if spill:
            raise ValueError("tea spilled")
        print("finished")
    finally:
        print("book returned")

borrow(False)
try:
    borrow(True)
except ValueError as e:
    print("problem:", e)
finally runs on the way out either way: after a normal finish, and before the error carries on.

Why with instead of try/finally? Both make sure clean-up happens. with puts the setup and the clean-up in one place, owned by the object that knows how to do them, so you can't forget one half, and the code reads as "while I have this file open, do this".

Mistakes and edge cases.

  • with on something that isn't a context manager. with 5 as x: gives TypeError: 'int' object does not support the context manager protocol (missed __exit__ method).
  • Using the resource after the block. The file is closed once the block ends.
  • Expecting with to catch the error. It cleans up, then the error carries on; add try/except if you want to handle it.

Quiz

  1. What does this print?

    try:
        print("start")
        x = 1 / 0
        print("never")
    except ZeroDivisionError:
        print("caught")
    finally:
        print("clean up")
  2. When does the clean-up of a with block run?

    • Every time the block ends, even after an error
    • Only if the block finishes without an error
    • Only when you call close()
  3. What does this print?

    with open("a.txt", "w") as f:
        f.write("hi")
    print(f.closed)
  4. What does this print?

    def lend():
        try:
            return "lent"
        finally:
            print("returned")
    
    print(lend())
  5. Which line has a mistake? (The file should be read inside the with block.)

    with open("a.txt", "w") as f:
        f.write("hello")
    with open("a.txt") as f:
        pass
    print(f.read())

Coding tasks

  1. Write first_line(name) that returns the first line of the file, without its newline. Use with.

  2. Write log_lines(name, lines) that adds each line (with a newline) to the end of the file, then reads the file back and returns how many lines it has now. Close the file before reading it back, or the new lines may not be saved yet.

  3. Write run_safely(func): call func(); return "ok" if it works, or "error" if it raises a ValueError. Either way, append "cleaned up" to the list log.