@contextmanager
- Python course
- Intermediate
- Lesson 108/116
- 5 min
Learn decorator-based context managers with @contextmanager.
@contextmanager
The @contextmanager decorator turns a function into a context manager. No need to write a class; a single yield separates opening and closing:
from contextlib import contextmanager
@contextmanager
def blok():
print("başla")
yield
print("bitir")
with blok():
print("içeride")Code before yield acts as __enter__, code after as __exit__. This is shorter than writing a class.
The contextlib module is in the standard library.
yield and sending a value
yield can also return a value. This value is captured with as:
@contextmanager
def kaynak():
print("aç")
yield "veri"
print("kapat")
with kaynık() as r:
print(r) # veriHere yield "veri" is bound to r via as r. The value yielded is used inside the with block.
This corresponds to the return value of __enter__ in the class-based approach.
Practice Write a block with @contextmanager
Write from contextlib import contextmanager. Define def blok(): with @contextmanager. In the body write print("başla"), yield, print("bitir"). Then inside with blok(): write print("içeride").
Starter code
# take contextmanager from contextlib
# make the blok function a context managerSample solution
from contextlib import contextmanager
@contextmanager
def blok():
print("başla")
yield
print("bitir")
with blok():
print("içeride")Expected output
başla içeride bitir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match @contextmanager
| Term | Meaning |
|---|---|
@contextmanager |
Decorator |
yield |
Split point |
before yield |
__enter__ |
after yield |
__exit__ |
2 What does yield do in @contextmanager?
- Separates opening and closing Correct answer
- Stops the block
- Raises an error
- Deletes a variable
Explanation: Code before yield is opening, after is closing.
3 Complete the yield keyword
@contextmanager
def blok():
print("başla")
____
print("bitir")
@contextmanager
def blok():
print("başla")
yield
print("bitir")
Explanation: yield separates opening and closing.