What are context managers and generators in Python? Where do you use them in backend code?
Asked at
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]
Also asked at ГК МЕДСИ
- [name] asked: How does memory management work in Python (garbage collector, reference counting)?
- What is the difference between TaskGroup and the gather function in the asyncio library in Python?
- What solutions did you implement to work around ChatGPT being unavailable from Russian IP addresses?
- How do you scale web application workers (for example, in FastAPI or Django), and which server did you use on your project?
- What blocks the event loop, how do you detect it in production, and what should you do about blocking code?
Similar questions
- What is a context manager in Python, how does it work, and how does it differ from a decorator?
- What is a context manager, how can you implement one yourself, and when have you used one?
- What is a generator?
- What are generators and iterators, and how do they differ? Can you write a generator without yield, and when should you write your own iterator?
- How does `with` and the context manager work?