__enter__ and __exit__
- Python course
- Intermediate
- Lesson 107/116
- 5 min
Learn to write context managers with __enter__ and __exit__.
__enter__ and __exit__
To make a class a context manager two methods are defined: __enter__ runs at the start of the block and returns the resource; __exit__ runs at the end and does cleanup:
class Kaynak:
def __enter__(self):
print("aç")
return self
def __exit__(self, *args):
print("kapat")These two methods make the with statement work. __exit__ takes three more arguments — they carry exception info.
This is the way to define a class-based context manager.
__exit__ and exception info
The __exit__ method takes three extra arguments: exc_type, exc_val, exc_tb. They carry info when an error occurs inside the block. If no error they are all None:
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print("hata oluştu")
print("kapat")If __exit__ returns True the error is suppressed — it does not propagate outside the with block. If it returns False or None the error propagates normally.
This enables error management inside a context manager.
Practice Write a class-based context manager
Define class Kaynak:. In __enter__ write print("aç") and return self. In __exit__ write print("kapat"). Then inside a with Kaynak(): block write print("içeride").
Starter code
# make the Kaynak class a context manager
# use it with withSample solution
class Kaynak:
def __enter__(self):
print("aç")
return self
def __exit__(self, *a):
print("kapat")
with Kaynak():
print("içeride")Expected output
aç içeride kapat
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the __enter__ method
class Kaynak:
def ____(self):
print("aç")
return self
class Kaynak:
def __enter__(self):
print("aç")
return self
Explanation: __enter__ runs at the start of the with block.
2 Match __enter__/__exit__
| Term | Meaning |
|---|---|
__enter__ |
Block entry |
__exit__ |
Block exit |
exc_type |
Error type |
return True |
Suppress error |
3 What happens if __exit__ returns True?
- The error is raised twice
- The program crashes
- The block reruns
- The error is suppressed Correct answer
Explanation: If __exit__ returns True the error is suppressed and does not propagate outside with.