with
A context manager: automatic setup and cleanup of resources.
Example
#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}")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
#with expression as name:
...More examples
#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())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 rememberclose(), 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
#- open()Opens a file for reading or writing and returns a file object.
- try, except, else, finallyException handling: catching errors without stopping the program.
- yieldCreates a generator: a function that returns successive values on demand.
- classDefines a class: a template for objects that combines data with the functions that act on it.
Spotted a mistake or missing an example? Write to us.