Context Managers

with statement and resource management

Interview Relevant: Pythonic resource handling

Context Managers

Use with to manage resources safely.

Code Examples

python
1with open("file.txt", "w") as f:
2    f.write("Hello")
3# f is automatically closed
4
5# Custom context manager
6class MyContext:
7    def __enter__(self):
8        print("Entering")
9        return self
10    def __exit__(self, exc_type, exc_val, exc_tb):
11        print("Exiting")

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In