NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

What are context managers and generators in Python? Where do you use them in backend code?

Practice

AI answer

A context manager manages a resource according to the “acquire — use — reliably release” pattern, including when an exception occurs. It usually implements __enter__/__exit__; for simple cases, you can use contextlib. For example, with open(path) as f: closes the file after the block. In back-end development, the same pattern is used with transactions, locks, and temporary resources.

A generator is an iterator that yields values one at a time using yield, without collecting the entire result in memory. It is useful for streaming large datasets, paginated results, or reading data in chunks. For example:

def batches(items, size):
    for i in range(0, len(items), size):
        yield items[i:i + size]