Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleCommonPractical

Implement a context manager that measures how long a block takes and still records the elapsed time if the block raises.

Answer

A class-based context manager can capture `perf_counter()` in `__enter__` and compute elapsed time in `__exit__`. Because `__exit__` runs when the `with` block exits even through an exception, timing is recorded on both success and failure. Returning `False` or `None` from `__exit__` lets the original exception propagate normally.

Strong answer includes

  • uses __enter__ and __exit__
  • uses a monotonic high-resolution timer such as perf_counter
  • does not accidentally suppress exceptions

Practical example

Class-based timer
Python
editable · browser sandbox
Result
Run the code to see the result.

Returning the timer from __enter__ exposes its elapsed field after the block; returning False from __exit__ preserves normal exception propagation.

Expected result: True.

#context-managers#timing#resource-safety

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocolscontextlib — Utilities for with-statement contextsPython Software Foundation · Context manager helpers, including contextmanager and ExitStackThe Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules