Context Managers

Published by Brayan K

Context managers are one of Python's most elegant and powerful tools — used everywhere from file handling, database transactions, network requests, locks, concurrency, and resource safety.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

with calls two methods, and any class can have them

This lesson is about how with works and how to write your own context managers, with files, a database-style transaction, a lock and a safe file writer as the examples. Network requests have HTTP Requests & APIs and Network Programming with sockets, and running work at the same time has Concurrency in Python: Threads vs Processes.

A with block calls two methods on the object written after with: __enter__ when the block starts and __exit__ when it ends. You don't call them yourself, just as you don't call __str__ when print() uses it, which Object-Oriented Programming showed. Any class that has both methods can go after with:

class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print("start", self.title)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("end", self.title)

with Section("report") as s:
    print("inside", s.title)
print("after the block")

# ✅ Expected output:
# start report
# inside report
# end report
# after the block

An object with these two methods is a context manager. A file is one: open() returns an object that has both, and its __exit__ is what closes it. File Handling said a with block closes the file even when an error stops the program; here is the method that does it, called by hand:

f = open("todo.txt", "w", encoding="utf-8")
print(hasattr(f, "__enter__"), hasattr(f, "__exit__"))
print(f.__enter__() is f)
f.write("tea\n")
f.__exit__(None, None, None)
print(f.closed)

# ✅ Expected output:
# True True
# True
# True

An object without the two methods can't go after with. On Python 3.11 to 3.13 that stops with TypeError: 'Box' object does not support the context manager protocol (for a class called Box), and 3.14 adds (missed __exit__ method) to the end. On 3.10 the error is AttributeError: __enter__.

as gets what __enter__ returns

The name after as gets whatever __enter__ returns, not the object written after with. Most context managers return self, but they don't have to. This shelf hands out its list:

class Shelf:
    def __init__(self, name):
        self.name = name
        self.items = []

    def __enter__(self):
        print("open", self.name)
        return self.items

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name, self.items)

with Shelf("books") as items:
    items.append("Dune")
    print(type(items).__name__)

# ✅ Expected output:
# open books
# list
# close books ['Dune']

Leave out the return and __enter__ returns None, so the name after as is None. Nothing complains until the block uses it:

class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print("start", self.title)

    def __exit__(self, exc_type, exc, tb):
        print("end", self.title)

with Section("report") as s:
    print(s)
    print(s.title)

# ✅ Expected output:
# start report
# None
# end report

# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'title'

end report still printed, because __exit__ runs even when the block fails. Without as, nothing uses what __enter__ returns, so a missing return goes unnoticed.

The object after with is made before the block starts. open() opens the file right there, so a missing file fails in open(), before with calls anything:

f = open("todo.txt", "w", encoding="utf-8")
print(f.closed)
with f:
    f.write("tea\n")
print(f.closed)

try:
    with open("notes.txt", encoding="utf-8") as g:
        print("never reached")
except FileNotFoundError as e:
    print(type(e).__name__, e.filename)

# ✅ Expected output:
# False
# True
# FileNotFoundError notes.txt

The example prints the error's name and the file name rather than the whole message, because the message includes an error number: 2 in python3, 44 in this site's editor.

The cleanup runs however the block ends

__exit__ runs when the block ends, whichever way it ends. An error stops the block, and __exit__ runs before the error reaches the except:

class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print("start", self.title)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("end", self.title)

try:
    with Section("risky"):
        print("working")
        int("12a")
        print("not reached")
except ValueError as e:
    print("caught:", e)

# ✅ Expected output:
# start risky
# working
# end risky
# caught: invalid literal for int() with base 10: '12a'

A return inside the block ends it too, and so do break and continue in a loop:

class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print("start", self.title)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("end", self.title)

def first_long_word(text):
    with Section("search"):
        for word in text.split():
            if len(word) > 3:
                return word
    return None

print(first_long_word("tea and biscuits"))

# ✅ Expected output:
# start search
# end search
# biscuits
class Section:
    def __init__(self, title):
        self.title = title

    def __enter__(self):
        print("start", self.title)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("end", self.title)

for n in [1, 2, 3]:
    with Section(n):
        if n == 1:
            continue
        if n == 2:
            break
print("loop done")

# ✅ Expected output:
# start 1
# end 1
# start 2
# end 2
# loop done

This is the cleanup a finally does. Exception Handling wrote a file in a with block that failed halfway; written out with try and finally instead, it prints the same three lines:

from pathlib import Path

f = open("log.txt", "w", encoding="utf-8")
try:
    try:
        f.write("started\n")
        f.write(10)
    finally:
        f.close()
except TypeError as e:
    print("Caught:", e)
print("Closed:", f.closed)
print(repr(Path("log.txt").read_text(encoding="utf-8")))

# ✅ Expected output:
# Caught: write() argument must be str, not int
# Closed: True
# 'started\n'

The language reference spells out exactly what with does. It isn't a program to run, but it is the whole rule:

manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(manager, None, None, None)

In words: Python takes the two methods from the object's class and calls __enter__; what it returns goes to the name after as (TARGET), and the block (SUITE) runs. If an error stops the block, __exit__ gets the error, and its answer decides whether the error carries on. If the block ends any other way, __exit__ gets three Nones.

__exit__ is told about the error, and decides what happens to it

After self, __exit__ takes three values: the error's class, the error itself, and a traceback, the record of where the error happened that Python prints when an error stops a program. When the block ends without an error, all three are None:

class Show:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        print(exc_type, exc, type(tb).__name__)

with Show():
    print("no error")

try:
    with Show():
        prices = {"tea": 2}
        prices["coffee"]
except KeyError:
    print("the KeyError carried on")

# ✅ Expected output:
# no error
# None None NoneType
# <class 'KeyError'> 'coffee' traceback
# the KeyError carried on

A KeyError shows its key in quotes, as Exception Handling said. Don't print the traceback itself: its text includes a memory address, which changes on every run.

What __exit__ returns decides what happens to the error. Return True and Python swallows it: the rest of the block is skipped, and the program carries on after the with:

class Swallow:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        print("swallowing", exc_type.__name__ if exc_type else None)
        return True

with Swallow():
    print(10 / 0)
    print("not reached")
print("the program carries on")

# ✅ Expected output:
# swallowing ZeroDivisionError
# the program carries on

Any true value swallows it, as any true value passes an if. Returning nothing gives None, which lets the error through, and that is the usual choice:

class Says:
    def __init__(self, answer):
        self.answer = answer

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        return self.answer

for answer in ["yes", 1, None, 0, ""]:
    try:
        with Says(answer):
            raise ValueError("bad")
        print(repr(answer), "swallowed it")
    except ValueError:
        print(repr(answer), "let it through")

# ✅ Expected output:
# 'yes' swallowed it
# 1 swallowed it
# None let it through
# 0 let it through
# '' let it through

Swallowing every error hides bugs. Here a typo, itme for item, makes the loop fail with a NameError on its first pass; the context manager swallows it, and the total silently stays 0:

class Quiet:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        return True

prices = {"tea": 2, "cake": 3}
total = 0
with Quiet():
    for item in ["tea", "cake"]:
        total += prices[itme]
print(total)

# ✅ Expected output:
# 0

So check the error's class and swallow only the kind you expect. Returning False, or nothing, lets every other error through:

class SkipMissing:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        if exc_type is KeyError:
            print("skipped", exc)
            return True
        return False

prices = {"tea": 2}
with SkipMissing():
    print(prices["coffee"])
print("carried on")
with SkipMissing():
    print(prices["tea"] / 0)

# ✅ Expected output:
# skipped 'coffee'
# carried on

# ✅ Expected error:
# ZeroDivisionError: division by zero

The standard library's contextlib.suppress(KeyError) does this in one line; contextlib: contextmanager, suppress, ExitStack covers it.

When __enter__ fails, __exit__ doesn't run

__exit__ cleans up after a block that started. If __enter__ itself fails, the block never starts, so Python doesn't call __exit__:

class Report:
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        print("opening", self.path)
        self.file = open(self.path, encoding="utf-8")
        return self.file

    def __exit__(self, exc_type, exc, tb):
        print("closing", self.path)
        self.file.close()

try:
    with Report("missing.txt") as f:
        print(f.read())
except FileNotFoundError as e:
    print("caught:", type(e).__name__, e.filename)

# ✅ Expected output:
# opening missing.txt
# caught: FileNotFoundError missing.txt

That is the right call. This __exit__ closes self.file, which __enter__ never got to make; calling it by hand after the failed __enter__ shows what would have happened:

class Report:
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        self.file = open(self.path, encoding="utf-8")
        return self.file

    def __exit__(self, exc_type, exc, tb):
        self.file.close()

r = Report("missing.txt")
try:
    r.__enter__()
except FileNotFoundError:
    print("__enter__ failed")
r.__exit__(None, None, None)

# ✅ Expected output:
# __enter__ failed

# ✅ Expected error:
# AttributeError: 'Report' object has no attribute 'file'

So when __enter__ sets up two things and the second fails, nothing calls __exit__ for the first. __enter__ has to undo its own work before it lets the error go on, and raise on its own, as in Exception Handling, passes the same error on:

class Session:
    def __enter__(self):
        self.log = open("session.log", "w", encoding="utf-8")
        try:
            self.config = open("settings.ini", encoding="utf-8")
        except FileNotFoundError:
            self.log.close()
            raise
        return self

    def __exit__(self, exc_type, exc, tb):
        self.config.close()
        self.log.close()

s = Session()
try:
    with s:
        print("working")
except FileNotFoundError as e:
    print("caught:", e.filename)
print("log closed:", s.log.closed)

# ✅ Expected output:
# caught: settings.ini
# log closed: True

Without the inner try, the same program prints log closed: False: the log file stays open after the error. contextlib.ExitStack, from the contextlib lesson linked above, keeps track of several such steps for you.

Several context managers in one with

One with can manage several objects, separated by commas. They are entered left to right and cleaned up in reverse, so the last one opened is the first one closed:

class Res:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("open", self.name)
        return self.name

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name)

with Res("a") as a, Res("b") as b:
    print("using", a, b)

# ✅ Expected output:
# open a
# open b
# using a b
# close b
# close a

If one of them fails to enter, the ones already entered are still cleaned up, and the ones after it are never opened:

class Res:
    def __init__(self, name, fail=False):
        self.name = name
        self.fail = fail

    def __enter__(self):
        print("open", self.name)
        if self.fail:
            raise OSError(f"cannot open {self.name}")
        return self

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name)

try:
    with Res("a"), Res("b", fail=True), Res("c"):
        print("body")
except OSError as e:
    print("caught:", e)

# ✅ Expected output:
# open a
# open b
# close a
# caught: cannot open b

Commas have worked here since Python 3.1. Python 3.10 added brackets around the list, so that each context manager can go on its own line:

with (
    open("in.txt", "w", encoding="utf-8") as src,
    open("out.txt", "w", encoding="utf-8") as dst,
):
    src.write("tea\n")
    dst.write("TEA\n")
print(src.closed, dst.closed)

# ✅ Expected output:
# True True

@contextmanager: the two halves in one function

Decorators & Advanced Features showed @contextmanager, which turns a function into something with can use. It relies on yield: a function that contains yield stops there, hands the value out, and carries on from the same place later. Generators & Iterators Mastery covers yield in full. Here it splits the function in two: the code before yield is the __enter__, the value it yields goes to as, and the code after it is the __exit__:

from contextlib import contextmanager

@contextmanager
def section(title):
    print("start", title)
    try:
        yield title.upper()
    finally:
        print("end", title)

with section("report") as heading:
    print("inside", heading)

try:
    with section("risky"):
        raise ValueError("bad row")
except ValueError as e:
    print("caught:", e)

# ✅ Expected output:
# start report
# inside REPORT
# end report
# start risky
# end risky
# caught: bad row

The try and finally around yield matter. When the block fails, the error comes out of the yield, so without finally the code after it is skipped and the cleanup never runs:

from contextlib import contextmanager

@contextmanager
def section(title):
    print("start", title)
    yield
    print("end", title)

try:
    with section("risky"):
        raise ValueError("bad row")
except ValueError as e:
    print("caught:", e)

# ✅ Expected output:
# start risky
# caught: bad row

The function must reach exactly one yield. Without one, it isn't a generator at all, and with fails as soon as the function returns:

from contextlib import contextmanager

@contextmanager
def section(title):
    print("start", title)

with section("report"):
    print("inside")

# ✅ Expected output:
# start report

# ✅ Expected error:
# TypeError: 'NoneType' object is not an iterator

With a second yield, the block runs and Python refuses after it:

from contextlib import contextmanager

@contextmanager
def section(title):
    print("start", title)
    yield
    print("end", title)
    yield

with section("report"):
    print("inside")

# ✅ Expected output:
# start report
# inside
# end report

# ✅ Expected error:
# RuntimeError: generator didn't stop

A function that returns before it reaches its yield stops with RuntimeError: generator didn't yield. The rest of the contextlib module, including how an error reaches the generator and why one of these objects can't be used twice, is in contextlib: contextmanager, suppress, ExitStack.

Three jobs for a context manager: a transaction, a lock and a safe write

A context manager fits anything that must be undone, given back or put right when the block ends. A database transaction either keeps all of its changes or none of them. This one copies the accounts when it starts and puts the copy back if the block fails, so a transfer that would overdraw an account changes nothing:

class Transaction:
    def __init__(self, accounts):
        self.accounts = accounts

    def __enter__(self):
        self.saved = self.accounts.copy()
        return self.accounts

    def __exit__(self, exc_type, exc, tb):
        if exc_type is None:
            print("committed")
        else:
            self.accounts.clear()
            self.accounts.update(self.saved)
            print("rolled back:", exc)

def transfer(accounts, src, dst, amount):
    accounts[src] -= amount
    if accounts[src] < 0:
        raise ValueError(f"{src} would be overdrawn")
    accounts[dst] += amount

accounts = {"ada": 50, "bob": 10}
with Transaction(accounts) as acc:
    transfer(acc, "ada", "bob", 20)
print(accounts)

try:
    with Transaction(accounts) as acc:
        transfer(acc, "bob", "ada", 40)
except ValueError as e:
    print("refused:", e)
print(accounts)

# ✅ Expected output:
# committed
# {'ada': 30, 'bob': 30}
# rolled back: bob would be overdrawn
# refused: bob would be overdrawn
# {'ada': 30, 'bob': 30}

clear() and update() put the copy's contents back into the same dictionary, so accounts outside the block sees them. Real databases do this for you, and Using SQLite & ORMs (SQLAlchemy) in Python shows sqlite3's version.

A lock lets one part of a program at a time use something shared, such as a total that several threads update. threading.Lock is a context manager: with takes the lock and gives it back when the block ends, even after an error, so it is never left locked. This site's editor can't start threads, so the example shows only the lock; Concurrency in Python: Threads vs Processes puts it to work.

import threading

lock = threading.Lock()
with lock:
    print("inside:", lock.locked())
print("after:", lock.locked())

try:
    with lock:
        raise ValueError("bad update")
except ValueError:
    print("after an error:", lock.locked())

# ✅ Expected output:
# inside: True
# after: False
# after an error: False

Opening a file with "w" empties it straight away, so a program that crashes halfway through writing leaves half a file behind:

from pathlib import Path

Path("config.txt").write_text("volume=3\n", encoding="utf-8")
try:
    with open("config.txt", "w", encoding="utf-8") as f:
        f.write("volume=")
        raise RuntimeError("crashed halfway")
except RuntimeError as e:
    print("caught:", e)
print(repr(Path("config.txt").read_text(encoding="utf-8")))

# ✅ Expected output:
# caught: crashed halfway
# 'volume='

A safer writer writes to a temporary file next to the real one. Only when the block succeeds does it swap the new file in, with Path.replace(), which renames a file over another; after an error it deletes the temporary file, so the old settings survive:

from pathlib import Path

class SafeWriter:
    def __init__(self, path):
        self.path = Path(path)
        self.temp = self.path.with_name(self.path.name + ".tmp")

    def __enter__(self):
        self.file = open(self.temp, "w", encoding="utf-8")
        return self.file

    def __exit__(self, exc_type, exc, tb):
        self.file.close()
        if exc_type is None:
            self.temp.replace(self.path)
        else:
            self.temp.unlink()

folder = Path("settings")
folder.mkdir()
config = folder / "config.txt"
config.write_text("volume=3\n", encoding="utf-8")

with SafeWriter(config) as f:
    f.write("volume=5\n")
print(config.read_text(encoding="utf-8"), end="")

try:
    with SafeWriter(config) as f:
        f.write("volume=")
        raise RuntimeError("crashed halfway")
except RuntimeError as e:
    print("caught:", e)
print(config.read_text(encoding="utf-8"), end="")
print(sorted(p.name for p in folder.iterdir()))

# ✅ Expected output:
# volume=5
# caught: crashed halfway
# volume=5
# ['config.txt']

Practice: a basket that reports what isn't on the menu

Each customer's order goes into a basket in a with block. An item that isn't on the menu raises a KeyError: the basket should report it and let the till carry on, without hiding any other error. Fill the three blanks: the method with calls first, what that method returns, and the one kind of error to swallow. Each hint line under the code gives one blank, in order.

class Basket:
    def __init__(self, name):
        self.name = name
        self.items = []

    def ___(self):
        print("open", self.name)
        return ___

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name, self.items)
        if exc_type is ___:
            print("not on the menu:", exc)
            return True
        return False

menu = {"tea": 2, "cake": 3}

with Basket("Ada") as basket:
    basket.items.append(menu["tea"])
    basket.items.append(menu["cake"])

with Basket("Bob") as basket:
    basket.items.append(menu["tea"])
    basket.items.append(menu["soup"])

print("till still open")

# 👉 replace ___ with __enter__
# 👉 replace ___ with self
# 👉 replace ___ with KeyError

# ✅ Expected output:
# open Ada
# close Ada [2, 3]
# open Bob
# close Bob [2]
# not on the menu: 'soup'
# till still open

With a bare return in the second blank, basket is None and Ada's first item stops the program with AttributeError: 'NoneType' object has no attribute 'items'. With ValueError in the third, Bob's basket still closes, but the KeyError carries on and the program stops with KeyError: 'soup'.

On your own: tags that always close

Write a class Tag. with Tag("p"): prints <p> before the block and </p> after it, even when the block fails, and doesn't hide the error.

Use it to print a list of two items, tea and milk, each in an li tag inside a ul tag. Then print a paragraph whose body divides by zero, and catch the ZeroDivisionError outside the with, printing error: and the message.

# Write the Tag class here, then use it.

# your code here
class Tag:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f"<{self.name}>")
        return self

    def __exit__(self, exc_type, exc, tb):
        print(f"</{self.name}>")
        return False

with Tag("ul"):
    for item in ["tea", "milk"]:
        with Tag("li"):
            print(item)

try:
    with Tag("p"):
        print(10 / 0)
except ZeroDivisionError as e:
    print("error:", e)

# ✅ Expected output:
# <ul>
# <li>
# tea
# </li>
# <li>
# milk
# </li>
# </ul>
# <p>
# </p>
# error: division by zero

Practice quiz

Box's __enter__ prints A and its __exit__ prints B. Inside try:, the block with Box(): prints C, runs 1 / 0, then prints D, and except ZeroDivisionError: prints E. What is printed, in order?

  • A, C, D, B, E
  • A, C, E
  • A, C, B, E
  • A, C, E, B

Answer: A, C, B, E. The error stops the block before D. __exit__ runs on the way out (B), and then the error reaches the except (E).

Box's __init__ sets self.label = "tea", its __enter__ prints open and has no return line, and its __exit__ prints close. What does with Box() as b: print(b.label) do?

  • open, close, then it stops with AttributeError: 'NoneType' object has no attribute 'label'
  • It prints tea
  • open, tea, close
  • It stops with AttributeError before anything prints

Answer: open, close, then it stops with AttributeError: 'NoneType' object has no attribute 'label'. Without a return, __enter__ returns None, so b is None. __exit__ still runs as the error leaves the block.

Box's __exit__ returns True. The block with Box(): runs x = int("five"), and the line after the block prints done. What happens?

  • It stops with ValueError: invalid literal for int() with base 10: 'five'
  • It prints done
  • Nothing is printed
  • It prints True, then done

Answer: It prints done. Returning True from __exit__ swallows the ValueError, so the program carries on after the with.

Box's __enter__ raises ValueError("no") and its __exit__ prints closed. Inside try:, with Box(): print("body"), and except ValueError: prints caught. What is printed?

  • caught
  • closed, then caught
  • body, closed, caught
  • It stops with ValueError: no

Answer: caught. The block never started, so Python doesn't call __exit__, and the error goes straight to the except.

Box(n)'s __enter__ prints in n and its __exit__ prints out n. What does with Box(1), Box(2): pass print?

  • in 1, in 2, out 1, out 2
  • in 1, out 1, in 2, out 2
  • in 2, in 1, out 1, out 2
  • in 1, in 2, out 2, out 1

Answer: in 1, in 2, out 2, out 1. Managers are entered left to right and cleaned up in reverse, so the last one in is the first one out.

A @contextmanager function prints open, yields, then prints close, with no try/finally around the yield. Inside try:, its with block raises KeyError("k"), and except KeyError: prints caught. What is printed?

  • open, close, caught
  • open, caught, close
  • open, caught
  • It stops with KeyError: 'k'

Answer: open, caught. The error comes out of the yield, so without finally the code after yield never runs.

Box's __exit__ prints closed. get() runs with Box(): return "value". What does print(get()) show?

  • value
  • value, then closed
  • closed
  • closed, then value

Answer: closed, then value. The return ends the block, so __exit__ runs before get() hands back its value, and print() shows the value after that.

Skip's __exit__ returns exc_type is KeyError. One with Skip(): block runs {}["x"], then the program prints one; a second with Skip(): block runs [][0], then it prints two. What happens?

  • one, two
  • one, then it stops with IndexError: list index out of range
  • It stops with KeyError: 'x'
  • one

Answer: one, then it stops with IndexError: list index out of range. The KeyError is swallowed, so one prints. For the IndexError, __exit__ returns False, so it carries on and stops the program before two.

Continue this course

Frequently asked questions

Does a with block have its own variables?

No. A name made inside the block, and the name after as, are still there after it, as with an if block. After with open("a.txt", "w", encoding="utf-8") as f: first = "tea", the line print(first, f.name, f.closed) prints tea a.txt True: the file object is still there, closed.

Can I use one context manager twice?

A class-based one, yes, as long as its __enter__ sets things up again each time: entering the same object twice prints in, out, in, out. A file can't be used twice, because the first with closed it: the second with stops with ValueError: I/O operation on closed file. A @contextmanager object can't either, so call the function again to get a fresh one.

What if __exit__ itself raises an error?

Its error replaces the one from the block, which Python keeps as the new error's __context__. A block that raises ValueError("bad row") under an __exit__ that raises RuntimeError("cleanup failed") ends with the RuntimeError, and printing repr(error.__context__) shows ValueError('bad row'). Custom Exceptions & Exception Chaining covers chained errors.

Does Ctrl+C still run the cleanup?

Yes. Pressing Ctrl+C raises KeyboardInterrupt inside the block, and __exit__ gets it like any other error: an __exit__ that prints the error's name prints KeyboardInterrupt. Exception Handling explains why except Exception doesn't catch it.

Does with sqlite3.connect(...) as conn close the connection?

No. With transaction control enabled, the connection's with block commits the current transaction on success or rolls it back after an error, and leaves the connection open. Earlier uncommitted inserts in that transaction can be rolled back too; previously committed changes remain. The block does not itself begin a new transaction. Close the connection with conn.close(). Using SQLite & ORMs (SQLAlchemy) in Python covers databases.

What is async with?

The same idea for code that waits, such as network requests: the object has __aenter__ and __aexit__ instead, and Python awaits them. It only works inside an async def. Advanced Async & Await Patterns and AsyncIO: Event Loop, Tasks & Futures cover async code.

Related lessons