medium +20 pts

Context manager from generator

Turn a generator function into a context manager using contextlib.

Create a function `managed_resource()` that returns a context manager using the `@contextmanager` decorator from the `contextlib` module. The context manager should: - Print `'entering'` when the context is entered, before yielding. - Yield the string `'resource'` to the `with` block. - Print `'exiting'` when leaving the context, regardless of whether an exception occurred inside the block. Implement `managed_resource()` so that the following behavior holds: ```python with managed_resource() as res: print(res) ``` prints exactly: ``` entering resource exiting ``` The function must be defined as `def managed_resource():` and use `yield`. Use the `@contextmanager` decorator from the `contextlib` module. Do not use a class or explicit try/finally — the decorator handles cleanup automatically after the yield. Your code should be a single generator function decorated with `@contextmanager`.

Constraints

No input parameters. The function must be callable with no arguments. It must yield exactly one value. Output must match exactly, including newlines.

Example

>>> with managed_resource() as r:
...     print(r)
entering
resource
exiting
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `yield` to produce the value and place print statements before and after it.
The `@contextmanager` decorator automatically handles cleanup, so you don't need try/finally.
Print 'entering' right before yield, and 'exiting' right after yield.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.