MemotivaContext managers and the with statement

What is the difference between with and try-finally?

Context managers and the with statement

Audio flashcard · 0:16

Nortren·

What is the difference between with and try-finally?

0:16

They achieve the same goal of guaranteed cleanup but with different syntax and semantics. The with statement is more concise and requires the resource to be a context manager. Try-finally is more flexible but more verbose. For files, locks, and database connections, with is the preferred idiom. ---
docs.python.org