Sobes.tech
Junior — Middle

How does the use of a context manager differ from a try/finally block when handling resources in Python?

sobes.tech AI

Answer from AI

The Python context manager (used via the with statement) automatically manages resources: it guarantees that the enter and exit methods will be called, allowing resources to be opened and closed correctly even if exceptions occur.

The try/finally block also allows resources to be released, but requires explicit calls to release methods in finally, which increases the likelihood of errors or omissions.

Example with a context manager:

with open('file.txt', 'r') as f:
    data = f.read()

Equivalent with try/finally:

f = open('file.txt', 'r')
try:
    data = f.read()
finally:
    f.close()

The context manager makes the code cleaner, safer, and more convenient for working with resources.