There are many uses. Just in the standard library we have:
sqlite3
; using the connection as a context manager translates to committing or aborting the transaction.unittest
; usingassertRaises
as a context manager lets you assert an exception is raised, then test aspects of the exception.decimal
;localcontext
manages decimal number precision, rounding, and other aspects.threading
objects such as locks, semaphores and conditions are context managers too; letting you obtain a lock for a set of statements, etc.the
warnings
module gives you a context manager to temporarily catch warnings.many libraries offer closing behaviour, just like the default file object. These include the
tarfile
and thezipfile
modules.Python's own
test.test_support
module uses several context managers, to check for specific warnings, capturestdout
, ignore specific exceptions and temporarily set environment variables.
Any time you want to detect when a block of code starts and / or ends, you want to use a context manager. Where before you'd use try:
with a finally:
suite to guarantee a cleanup, use a context manager instead.