with

A context manager: automatic setup and cleanup of resources.

On this page

Example

#
Python
from contextlib import contextmanager

@contextmanager
def lesson(title):
    print(f"Start: {title}")
    try:
        yield title.upper()
    finally:
        print(f"End: {title}")

with lesson("loops") as name:
    print(f"Learning: {name}")
Resultsaved result, you can check it
Start: loops
Learning: LOOPS
End: loops

Definition and usage

#

The with statement uses a context manager, which prepares a resource before the block and cleans it up afterward, even if an error occurs inside the block. The best-known example is opening a file: once the block exits, the file is closed automatically.

Thread locks, database connections, and temporary setting changes are also context managers, for example. You can use several at once, separated by commas.

You can write your own context manager as a class with __enter__ and __exit__ methods, or more simply, as a function decorated with @contextmanager from the contextlib module.

Syntax

#
Syntax
with expression as name:
    ...

More examples

#
Opening a file
Python
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("A for loop iterates over elements\n")

with open("notes.txt", encoding="utf-8") as file:
    print(file.read().strip())
Resultsaved result, you can check it
A for loop iterates over elements

The file will be closed after each with block, even if the write raised an error.

Good practices

#
  • Always open files through with. You do not have to remember close(), and the file is closed even after an error.
  • For text files, give encoding="utf-8" so accented characters behave the same on every system.

Related entries

#

Spotted a mistake or missing an example? Write to us.