CodeBlanks Logo Icon CodeBlanks

Summary - Context managers

Combine @contextmanager and ExitStack to write a resource pool.

Summary - Context managers

In this group you learned five core concepts:

  • with — auto-closes a resource
  • __enter__/__exit__ — class-based context manager
  • @contextmanager — function-based context manager
  • exception catching — suppressing errors in __exit__
  • ExitStack — dynamic multi-management

Now you will do two short tasks that combine them: one with a class-based CM, one with @contextmanager.

Practice Class-based context manager

Define class Log:. In __enter__ write print("aç") and return self. In __exit__ write print("kapat"). Inside a with Log(): block write print("çalışıyor").

Starter code

main.py
# make the Log class a context manager
# use it with with

Sample solution

main.py
class Log:
    def __enter__(self):
        print("aç")
        return self
    def __exit__(self, *a):
        print("kapat")

with Log():
    print("çalışıyor")

Expected output

aç
çalışıyor
kapat

Practice Block with @contextmanager

Write from contextlib import contextmanager. Define def blok(): with @contextmanager. In the body write print("başla"), yield, print("bitir"). Inside with blok(): write print("içeride").

Starter code

main.py
# take contextmanager from contextlib
# make the blok function a CM and use it

Sample solution

main.py
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 Which is the shortest way to write a context manager?

  • Class + __enter__/__exit__
  • try/finally
  • ExitStack
  • @contextmanager + yield Correct answer

Explanation: @contextmanager makes a CM from a function; no need to write a class.

2 Match context manager concepts

Term Meaning
with Starts the block
__enter__ Opening
__exit__ Closing
yield Split in CM

All lessons in Intermediate