easy +8 pts

Context Manager Class

Implement a context manager that measures execution time and sets duration based on exceptions.

Write a class `TimedContext` that can be used with the `with` statement. It must: - Accept a single argument `name` (a string) in its `__init__` method. - When entering the context, record the start time using `time.perf_counter()`. - When exiting, compute elapsed time as `time.perf_counter() - start_time`. - If no exception occurred during the block, store the elapsed time in an attribute `duration` (a float). - If an exception occurred, set `duration` to `None`. - In all cases, the `__exit__` method should return `False` (so exceptions propagate). Complete the class definition. Do not modify the `__init__` signature. The class will be used as: ```python with TimedContext('block') as tc: ... print(tc.duration) ``` Note: The duration attribute must be set after the block completes.

Constraints

- `name` will be a non-empty string. - The class must work in a `with` statement. - No additional attributes are required. - `__exit__` must accept the standard exception arguments `(exc_type, exc_val, exc_tb)`.

Example

```python
# Example 1: Normal execution
tc = TimedContext('fast')
with tc:
    sum(range(1000))
print(round(tc.duration, 6))  # prints a small non-negative float

# Example 2: Exception case
tc = TimedContext('boom')
try:
    with tc:
        raise ValueError('oops')
except ValueError:
    pass
print(tc.duration)  # prints None
```
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Inside __enter__, assign `self._start = time.perf_counter()` and return `self`.
In __exit__, compute `elapsed = time.perf_counter() - self._start`.
Check whether `exc_type is not None` to decide if an exception occurred.
Set `self.duration` to `elapsed` or `None` accordingly, then return `False`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.