A context manager in Python is an object that defines methods to manage resources, such as files, network connections, or database transactions, before and after their use. It allows you to allocate and release resources precisely when you need them.
It is most commonly used with the ‘with’ keyword and provides two magic methods:
1. `__enter__`: This method is called at the beginning of the with block.
1. `__exit__`: This method is called at the end of the with block. It handles the cleanup code, such as closing a file or a network connection.
An example of a context manager is when dealing with file operations:
```
with open(‘example.txt’, ‘w’) as my_file:
my_file.write(‘Hello, world!’)
```
In this case, ‘open’ is the context manager. The file ‘example.txt’ is opened, written to, and then automatically closed at the end of the with block, whether or not it was used successfully, ensuring resources are handled efficiently.