Decoding Python Magic : __enter__ and __exit__
Let’s understand how context managers work.
Hello Everyone,
Welcome to the next installment of my magic methods series! Today, let’s delve into understanding how the with
statement works in Python.
Context Manager
Context managers in Python are objects that are used to manage resources and define setup and cleanup actions that need to be performed around a block of code.
Some Use case of Context Managers
- File Handling: Managing file operations like opening and closing files.
- Database Connections: Managing connections to databases.
- Locking: Ensuring that only one thread or process accesses a resource at a time.
- Managing network connections
- Resource Management
Managing Files with Context Manager
One Operation that almost every developer does is to write into a file or read from a file. This operation is very common, Only precaution that we need to keep it, release assignedfd
.
Non Pythonic Way
f = None
try:
f = open("test.txt", "w")
f.write("Hello World")
finally:
if f:
f.close()
Class Based Context Manager
class FileContextManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.open_file = open(self.filename, "w")
return self.open_file
def __exit__(self, exc_type, exc_val, exc_tb):
self.open_file.close()
with FileContextManager("test.txt") as f:
f.write("Hello World")
Function based Context Managers
from contextlib import contextmanager
@contextmanager
def file_manager(filename):
f = open(filename, "w")
try:
yield f
finally:
f.close()
with file_manager("test.txt") as f:
f.write("Hello World")
How to close Sockets automatically?
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("localhost", 80))
s.sendall(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
print(s.recv(4096))
Conclusion
Context Managers are very useful and used heavily. These are mostly used to manage resources especially deallocate the occupied ones. Similar methods __aenter__
and __aexit__
are used to support async programming. If you want to learn it deeply, I already have a blog that covers pretty much everything.
Follow Rahul Beniwal for more programming tutorials.
Other similar articles by me.