Sobes.tech
Junior — Middle

Could you explain what a context manager in Python is and what it is used for?

sobes.tech AI

Answer from AI

A context manager in Python is an object that manages resources by ensuring their proper acquisition and release. It is typically used with the with statement to automatically perform setup actions upon entering the block and cleanup actions upon exiting, such as opening and closing a file.

This is convenient for working with files, network connections, locks, and other resources that require guaranteed release.

Example:

with open('file.txt', 'r') as f:
    data = f.read()
# the file is automatically closed after exiting the with block

To create your own context manager, you can implement the __enter__ and __exit__ methods in a class.