Назад к подготовке

Вопрос про production ML

What is a Python context manager, what do __enter__ and __exit__ do, and why not just wait for garbage collection?

Ответить самому

Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.

Загрузка

Короткий ответ

A context manager wraps setup and cleanup around a block. __enter__ prepares the resource, __exit__ runs even on exceptions, and this is safer than waiting for GC to close scarce OS resources.

Полный разбор

The with statement is syntax for entering and leaving a managed context. Python calls __enter__ before the block and __exit__ after the block, including when the block exits through an exception. Files, locks, transactions, sockets and temporary settings are common examples.

The reason is deterministic cleanup. Garbage collection is not a good resource-management policy for file descriptors, sockets, locks or database connections. These are external system resources with limits and side effects. Waiting until an object is eventually collected can keep handles open too long, leak locks, hold transactions or exhaust descriptors.

In ML code, the same pattern appears in things such as torch.no_grad or temporary precision/autocast contexts: the context manager makes state changes scoped and reversible.

Теория

Context managers encode a try/finally cleanup pattern behind a small protocol.

Типичные ошибки

  • Describe only files and miss the general protocol.
  • Assume GC cleanup is immediate and portable.
  • Forget exception behavior.

Как отвечать на собеседовании

  • Say deterministic cleanup explicitly.
  • Give one OS resource example and one ML/Python example.